mnml-rs 0.2.14

A NvChad-style terminal IDE in Rust — vim or standard editing, LSP, git, and an embedded HTTP client.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
//! The window layout: a binary split tree over the central pane area. The tree
//! rail, the bufferline, and the statusline live *outside* this tree. Each
//! [`Layout::Leaf`] references a pane (buffer) in `App::panes`. Invariants the
//! `App` methods maintain: **no buffer is in two leaves at once**, and the
//! *focused* buffer (`App::active`) is always in a leaf — so `active` uniquely
//! identifies the focused leaf. Buffers in *no* leaf are allowed (background tabs
//! the bufferline still lists); revealing one shows it in the focused leaf.

use ratatui::layout::Rect;

/// Index of a pane in `App::panes`.
pub type PaneId = usize;

/// How a split arranges its two children.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SplitDir {
    /// Side by side — `first` on the left, `second` on the right, vertical divider.
    Horizontal,
    /// Stacked — `first` on top, `second` below, horizontal divider.
    Vertical,
}

#[derive(Debug, Clone)]
pub enum Layout {
    Empty,
    /// A single split / leaf in the layout tree. May hold multiple
    /// tabs (panes); `active` is the currently visible one and is
    /// always present in `tabs`. `tabs` is non-empty and preserves
    /// insertion order (newest at end, except when explicitly
    /// reordered by drag-to-rearrange).
    Leaf {
        active: PaneId,
        tabs: Vec<PaneId>,
    },
    Split {
        dir: SplitDir,
        /// Percent of the split's long axis given to `first` (clamped 10..=90).
        ratio: u16,
        first: Box<Layout>,
        second: Box<Layout>,
    },
}

impl Layout {
    /// Convenience: make a single-tab leaf showing `id`.
    pub fn leaf(id: PaneId) -> Self {
        Layout::Leaf {
            active: id,
            tabs: vec![id],
        }
    }

    /// Convenience: leaf with multiple tabs, the given one active.
    /// Session restore uses this to synthesize a layout when the
    /// saved file had a stale `layout: null` but a non-empty
    /// `open[]` (qa-5th 2026-06-29 SEV-2).
    pub fn leaf_with_tabs(active: PaneId, tabs: Vec<PaneId>) -> Self {
        Layout::Leaf { active, tabs }
    }

    /// The active (visible) pane id for every leaf in the tree.
    /// Tab-stack siblings are NOT included — see `all_panes()`.
    pub fn leaves(&self) -> Vec<PaneId> {
        let mut out = Vec::new();
        self.collect_leaves(&mut out);
        out
    }

    /// Maximum recursion depth of the split tree. `0` for an empty
    /// layout or a single leaf; `1` for a single split; adds one per
    /// additional level. Used by #978's arbitrary-depth test to
    /// prove `split_active` genuinely nests without a hidden cap.
    pub fn max_depth(&self) -> usize {
        match self {
            Layout::Empty | Layout::Leaf { .. } => 0,
            Layout::Split { first, second, .. } => 1 + first.max_depth().max(second.max_depth()),
        }
    }
    fn collect_leaves(&self, out: &mut Vec<PaneId>) {
        match self {
            Layout::Empty => {}
            Layout::Leaf { active, .. } => out.push(*active),
            Layout::Split { first, second, .. } => {
                first.collect_leaves(out);
                second.collect_leaves(out);
            }
        }
    }

    /// Every pane referenced by the tree, including background
    /// tabs in multi-tab leaves. Used by garbage-collection logic
    /// that needs to know which `panes[i]` entries are still
    /// reachable from the layout.
    pub fn all_panes(&self) -> Vec<PaneId> {
        let mut out = Vec::new();
        self.collect_all_panes(&mut out);
        out
    }
    fn collect_all_panes(&self, out: &mut Vec<PaneId>) {
        match self {
            Layout::Empty => {}
            Layout::Leaf { tabs, .. } => out.extend(tabs.iter().copied()),
            Layout::Split { first, second, .. } => {
                first.collect_all_panes(out);
                second.collect_all_panes(out);
            }
        }
    }

    /// Find the leaf containing `pane` (as active OR background
    /// tab) and return a mutable ref to its (active, tabs) for
    /// Immutable counterpart to `leaf_containing_mut` — returns the
    /// leaf's tab list (the per-split tab group `pane` is part of)
    /// for read-only queries like "what tabs share this split?".
    pub fn leaf_containing(&self, pane: PaneId) -> Option<&[PaneId]> {
        match self {
            Layout::Leaf { tabs, .. } if tabs.contains(&pane) => Some(tabs.as_slice()),
            Layout::Split { first, second, .. } => first
                .leaf_containing(pane)
                .or_else(|| second.leaf_containing(pane)),
            _ => None,
        }
    }

    /// in-place mutation.
    pub fn leaf_containing_mut(&mut self, pane: PaneId) -> Option<(&mut PaneId, &mut Vec<PaneId>)> {
        match self {
            Layout::Leaf { active, tabs } if tabs.contains(&pane) => Some((active, tabs)),
            Layout::Split { first, second, .. } => first
                .leaf_containing_mut(pane)
                .or_else(|| second.leaf_containing_mut(pane)),
            _ => None,
        }
    }

    /// Find the leaf whose `active` pane is `target`.
    pub fn active_leaf_mut(&mut self, target: PaneId) -> Option<(&mut PaneId, &mut Vec<PaneId>)> {
        match self {
            Layout::Leaf { active, tabs } if *active == target => Some((active, tabs)),
            Layout::Split { first, second, .. } => first
                .active_leaf_mut(target)
                .or_else(|| second.active_leaf_mut(target)),
            _ => None,
        }
    }

    /// True when this layout contains at least one `Split` node.
    /// Used by `ui::draw` to hide the global bufferline when the
    /// per-leaf tab strips above each split would otherwise
    /// duplicate it.
    pub fn has_splits(&self) -> bool {
        matches!(self, Layout::Split { .. })
            || match self {
                Layout::Split { first, second, .. } => first.has_splits() || second.has_splits(),
                _ => false,
            }
    }

    /// The first (leftmost / topmost) leaf's active pane, if any.
    pub fn first_leaf(&self) -> Option<PaneId> {
        match self {
            Layout::Empty => None,
            Layout::Leaf { active, .. } => Some(*active),
            Layout::Split { first, second, .. } => {
                first.first_leaf().or_else(|| second.first_leaf())
            }
        }
    }

    pub fn contains(&self, p: PaneId) -> bool {
        self.all_panes().contains(&p)
    }

    /// Re-point the leaf whose ACTIVE pane is `from` to show `to`
    /// instead. Also rewrites the entry in `tabs` so the tab list
    /// stays consistent.
    pub fn set_leaf_pane(&mut self, from: PaneId, to: PaneId) {
        match self {
            Layout::Leaf { active, tabs } if *active == from => {
                if let Some(pos) = tabs.iter().position(|&t| t == from) {
                    tabs[pos] = to;
                } else {
                    tabs.push(to);
                }
                *active = to;
            }
            Layout::Split { first, second, .. } => {
                first.set_leaf_pane(from, to);
                second.set_leaf_pane(from, to);
            }
            _ => {}
        }
    }

    /// Find a `Split` whose direct children are both single-tab
    /// `Leaf`s wrapping `a` and `b` (in either order). Returns a
    /// mutable reference to that `Split` node so the caller can
    /// swap it out. Used by the Claude auto-tile: when the 3rd
    /// Claude opens and the existing two are in a leaf-only
    /// H-split, we rearrange that subtree into a 2×2 grid.
    ///
    /// Returns None if the two panes aren't in a clean leaf-only
    /// pair — a nested layout, multi-tab leaf, or unrelated
    /// grouping falls through to the caller's fallback.
    pub fn find_leaf_pair_split_mut(
        &mut self,
        a: PaneId,
        b: PaneId,
    ) -> Option<(&mut Layout, SplitDir)> {
        fn is_single_leaf_of(node: &Layout, pane: PaneId) -> bool {
            matches!(node, Layout::Leaf { active, tabs } if *active == pane && tabs.len() == 1 && tabs[0] == pane)
        }
        match self {
            Layout::Split {
                dir, first, second, ..
            } => {
                let matches_pair = (is_single_leaf_of(first, a) && is_single_leaf_of(second, b))
                    || (is_single_leaf_of(first, b) && is_single_leaf_of(second, a));
                if matches_pair {
                    let dir_copy = *dir;
                    Some((self, dir_copy))
                } else {
                    match self {
                        Layout::Split { first, second, .. } => first
                            .find_leaf_pair_split_mut(a, b)
                            .or_else(|| second.find_leaf_pair_split_mut(a, b)),
                        _ => None,
                    }
                }
            }
            _ => None,
        }
    }

    /// Smallest subtree whose leaves are exactly the given pane
    /// set (no more, no less — extra `Empty` nodes inside the
    /// subtree are allowed). Used by the Claude auto-tile to
    /// locate the "Claude cluster" subtree when growing the grid.
    ///
    /// Returns None if no such subtree exists (the pane set is
    /// spread across unrelated parts of the tree, or the tree
    /// contains other panes mixed in with the target set).
    pub fn find_pure_pane_cluster_mut(
        &mut self,
        set: &std::collections::HashSet<PaneId>,
    ) -> Option<&mut Layout> {
        fn matches(node: &Layout, set: &std::collections::HashSet<PaneId>) -> bool {
            let leaves = node.all_panes();
            leaves.len() == set.len() && leaves.iter().all(|p| set.contains(p))
        }
        fn contains_all(node: &Layout, set: &std::collections::HashSet<PaneId>) -> bool {
            let leaves = node.all_panes();
            set.iter().all(|p| leaves.contains(p))
        }
        // If neither this node nor a descendant contains the full
        // set, bail.
        if !contains_all(self, set) {
            return None;
        }
        // Prefer descending into whichever child still contains the
        // full set (i.e. tighter match). If neither does, this node
        // is the smallest wrapping subtree — return it if its
        // leaves match exactly.
        let descend = match self {
            Layout::Split { first, second, .. } => {
                if contains_all(first, set) {
                    Some(true)
                } else if contains_all(second, set) {
                    Some(false)
                } else {
                    None
                }
            }
            _ => None,
        };
        match (descend, self) {
            (Some(true), Layout::Split { first, .. }) => first.find_pure_pane_cluster_mut(set),
            (Some(false), Layout::Split { second, .. }) => second.find_pure_pane_cluster_mut(set),
            (_, node) => {
                if matches(node, set) {
                    Some(node)
                } else {
                    None
                }
            }
        }
    }

    /// Walk the tree and replace the first `Empty` node encountered
    /// (depth-first, first-child preferred) with `subtree`.
    /// Returns true if an `Empty` was found and replaced.
    pub fn fill_first_empty(&mut self, subtree: Layout) -> bool {
        match self {
            Layout::Empty => {
                *self = subtree;
                true
            }
            Layout::Leaf { .. } => false,
            Layout::Split { first, second, .. } => {
                if first.fill_first_empty(subtree.clone()) {
                    return true;
                }
                second.fill_first_empty(subtree)
            }
        }
    }

    /// #856 — `splits→tabs`. Collapse the entire tree into a single
    /// leaf whose `tabs` is every pane in the tree (in walk order:
    /// depth-first, first-side then second-side). Preserves the
    /// currently-active pane as the new `active` when possible.
    ///
    /// Idempotent: a single-leaf layout returns unchanged (aside
    /// from the fresh Vec allocation). Empty layouts stay Empty.
    ///
    /// Used by the `layout.merge_to_tabs` palette command +
    /// `Sessions view` chip. Reverse: [`Layout::spread_to_splits`].
    pub fn merge_to_tabs(&self, active_hint: PaneId) -> Layout {
        match self {
            Layout::Empty => Layout::Empty,
            _ => {
                let panes = self.all_panes();
                if panes.is_empty() {
                    return Layout::Empty;
                }
                let active = if panes.contains(&active_hint) {
                    active_hint
                } else {
                    panes[0]
                };
                Layout::Leaf {
                    active,
                    tabs: panes,
                }
            }
        }
    }

    /// #857 — `tabs→splits`. Take a single-leaf layout with N tabs
    /// and produce a split tree with each tab in its own leaf.
    /// Falls through unchanged if the layout is Empty or already
    /// has any splits (nothing sensible to spread).
    ///
    /// Layout choice matches the multi-Claude auto-tile heuristic
    /// (task #799) so the two features stay visually consistent:
    /// - 1 → single leaf (unchanged)
    /// - 2 → H-split (side by side)
    /// - 3 → left leaf + right V-split (2 stacked on the right)
    /// - 4 → 2×2 grid (H-split, each half V-split)
    /// - 5-6 → 3×2 grid (2 or 3 columns × 2 rows)
    /// - 7-8 → 4×2 grid
    /// - 9+ → caps at 8 splits, remaining tabs stack on the last
    ///   leaf as tabs (so no pane vanishes).
    ///
    /// Used by the `layout.spread_to_splits` palette command +
    /// Sessions view chip. Reverse: [`Layout::merge_to_tabs`].
    pub fn spread_to_splits(&self) -> Layout {
        let Layout::Leaf { tabs, active } = self else {
            return self.clone();
        };
        if tabs.len() <= 1 {
            return self.clone();
        }
        // Cap at 8 slots (last slot absorbs remainder as tabs).
        let n_slots = tabs.len().min(8);
        let (slot_tabs, tail) = tabs.split_at(n_slots.saturating_sub(1));
        // Build individual single-pane leaves for the first n-1 tabs.
        let mut leaves: Vec<Layout> = slot_tabs.iter().map(|&id| Layout::leaf(id)).collect();
        // Last leaf carries the remainder as tabs; active stays
        // whichever pane the caller had focused (falls back to
        // the first tail pane).
        let tail_active = if tail.contains(active) {
            *active
        } else {
            tail[0]
        };
        leaves.push(Layout::leaf_with_tabs(tail_active, tail.to_vec()));
        build_grid(&leaves, tabs.len().min(8))
    }

    /// True if the tree contains any `Empty` node.
    pub fn contains_empty(&self) -> bool {
        match self {
            Layout::Empty => true,
            Layout::Leaf { .. } => false,
            Layout::Split { first, second, .. } => {
                first.contains_empty() || second.contains_empty()
            }
        }
    }

    /// Replace the leaf whose ACTIVE pane is `target` with the
    /// subtree `with`. Used by `splice_pane_at` to swap a leaf
    /// for a Split in-place.
    pub fn replace_leaf(&mut self, target: PaneId, with: Layout) -> bool {
        match self {
            Layout::Leaf { active, .. } if *active == target => {
                *self = with;
                true
            }
            Layout::Split { first, second, .. } => {
                first.replace_leaf(target, with.clone()) || second.replace_leaf(target, with)
            }
            _ => false,
        }
    }

    /// Remove `target` from the tree:
    ///   - If `target` is a BACKGROUND tab in some leaf, just drop
    ///     it from that leaf's `tabs` (the leaf shape stays).
    ///   - If `target` IS the active tab AND the leaf has other
    ///     tabs, pop another tab as active (rightward neighbour
    ///     preferred, falling back to leftward).
    ///   - If `target` is the active tab AND the leaf is single-
    ///     tab, the leaf is dropped: if it's a child of a split
    ///     the split collapses into its sibling; if it's the root
    ///     the tree becomes `Empty`.
    /// Returns true if `target` was found.
    pub fn remove_leaf(&mut self, target: PaneId) -> bool {
        match self {
            Layout::Empty => false,
            Layout::Leaf { active, tabs } => {
                if !tabs.contains(&target) {
                    return false;
                }
                let is_active = *active == target;
                if let Some(pos) = tabs.iter().position(|&t| t == target) {
                    tabs.remove(pos);
                }
                if tabs.is_empty() {
                    *self = Layout::Empty;
                } else if is_active {
                    // Pick the new active: same-index (rightward
                    // neighbour) if available, else the previous tab.
                    let pos = tabs.iter().position(|&t| t == *active);
                    if pos.is_none() {
                        let idx = tabs.len().saturating_sub(1);
                        *active = tabs[idx];
                    }
                }
                true
            }
            Layout::Split { first, second, .. } => {
                // Try to remove from each child; if a child becomes Empty,
                // collapse this split into its sibling.
                let hit = first.remove_leaf(target) || second.remove_leaf(target);
                if hit {
                    if matches!(**first, Layout::Empty) {
                        *self = std::mem::replace(second, Box::new(Layout::Empty))
                            .as_ref()
                            .clone();
                    } else if matches!(**second, Layout::Empty) {
                        *self = std::mem::replace(first, Box::new(Layout::Empty))
                            .as_ref()
                            .clone();
                    }
                }
                hit
            }
        }
    }

    /// Walk the tree, find the smallest `Split` of direction `dir` that
    /// contains `target` (the active leaf), and adjust its ratio so the
    /// side `target` is in *grows* by `grow_delta` percent (so the chord
    /// "Ctrl+W +" always grows whichever pane the cursor is in). Clamped
    /// to 10..=90. Returns `true` if a matching split was found.
    pub fn adjust_split_ratio_for(
        &mut self,
        target: PaneId,
        dir: SplitDir,
        grow_delta: i32,
    ) -> bool {
        match self {
            Layout::Split {
                dir: this_dir,
                ratio,
                first,
                second,
            } => {
                let in_first = first.contains(target);
                let in_second = second.contains(target);
                if !in_first && !in_second {
                    return false;
                }
                // Recurse first — find the deepest matching split.
                let recursed = if in_first {
                    first.adjust_split_ratio_for(target, dir, grow_delta)
                } else {
                    second.adjust_split_ratio_for(target, dir, grow_delta)
                };
                if recursed {
                    return true;
                }
                if *this_dir == dir {
                    // The ratio is the share that goes to `first`. If the
                    // active leaf is in `first`, grow ⇒ raise the ratio. If
                    // in `second`, grow ⇒ lower it.
                    let signed = if in_first { grow_delta } else { -grow_delta };
                    let new_ratio = (*ratio as i32 + signed).clamp(10, 90) as u16;
                    *ratio = new_ratio;
                    return true;
                }
                false
            }
            _ => false,
        }
    }

    /// vim `Ctrl+W _` (height) / `Ctrl+W |` (width) — maximize the
    /// active leaf's allocation in the matching-direction split. Walks
    /// to the smallest enclosing split whose `dir == dir`, then pushes
    /// the ratio toward the side that contains `target`. Returns `true`
    /// when a ratio was changed.
    pub fn maximize_split_ratio_for(&mut self, target: PaneId, dir: SplitDir) -> bool {
        match self {
            Layout::Split {
                dir: this_dir,
                ratio,
                first,
                second,
            } => {
                let in_first = first.contains(target);
                let in_second = second.contains(target);
                if !in_first && !in_second {
                    return false;
                }
                let recursed = if in_first {
                    first.maximize_split_ratio_for(target, dir)
                } else {
                    second.maximize_split_ratio_for(target, dir)
                };
                if recursed {
                    return true;
                }
                if *this_dir == dir {
                    *ratio = if in_first { 90 } else { 10 };
                    return true;
                }
                false
            }
            _ => false,
        }
    }

    /// Swap the two sides of the smallest split that contains `target`.
    /// Vim `Ctrl+W r` rotates the splits at the cursor's level. Returns
    /// `true` if a swap was made (target was in a Split node).
    pub fn swap_siblings_containing(&mut self, target: PaneId) -> bool {
        match self {
            Layout::Split { first, second, .. } => {
                // If either side is the target's leaf or a subtree containing
                // it, recurse first; if the recursion couldn't find a deeper
                // Split, swap our own children.
                let in_first = first.contains(target);
                let in_second = second.contains(target);
                if !in_first && !in_second {
                    return false;
                }
                let recursed_first = if in_first {
                    first.swap_siblings_containing(target)
                } else {
                    false
                };
                let recursed_second = if in_second {
                    second.swap_siblings_containing(target)
                } else {
                    false
                };
                // If a deeper Split handled it, don't swap here.
                if recursed_first || recursed_second {
                    return true;
                }
                // Both children are Leafs (or one is, the other is Leaf-equivalent
                // for our purposes) — swap.
                std::mem::swap(first, second);
                true
            }
            _ => false,
        }
    }

    /// Reposition the active leaf within its immediate parent split. Vim
    /// `Ctrl+W H/J/K/L` "move to far edge" — this is a poor-man's version
    /// that operates on the *immediate* parent (not the outermost), so
    /// nested layouts only see a one-level rearrangement.
    /// `target_dir` is the direction the parent should end up as
    /// (`Horizontal` = side-by-side; `Vertical` = stacked). `to_second`
    /// puts the active leaf in `second` (right / bottom); else `first`
    /// (left / top). Returns true on a change.
    pub fn move_active_to(
        &mut self,
        target: PaneId,
        target_dir: SplitDir,
        to_second: bool,
    ) -> bool {
        match self {
            Layout::Split {
                dir, first, second, ..
            } => {
                let in_first = first.contains(target);
                let in_second = second.contains(target);
                if !in_first && !in_second {
                    return false;
                }
                // Recurse to the deepest split first.
                let recursed = if in_first {
                    first.move_active_to(target, target_dir, to_second)
                } else {
                    second.move_active_to(target, target_dir, to_second)
                };
                if recursed {
                    return true;
                }
                let mut changed = false;
                if *dir != target_dir {
                    *dir = target_dir;
                    changed = true;
                }
                // If the active is on the wrong side, swap children.
                if (in_first && to_second) || (in_second && !to_second) {
                    std::mem::swap(first, second);
                    changed = true;
                }
                changed
            }
            _ => false,
        }
    }

    /// Vim `Ctrl+W =` — equalize all splits so every LEAF renders
    /// at (approximately) the same size, regardless of tree shape.
    ///
    /// 2026-07-25 — rewritten from the old "50/50 at each level"
    /// approximation. The old impl produced 50/25/25 on an
    /// unbalanced 3-leaf tree (`Split(Leaf, Split(Leaf, Leaf))`);
    /// the user report: "when I open 4, close 1, and equalize,
    /// it makes 2 equal not 3." Delegates to `rebalance_leaves`
    /// which weights each Split node by the leaf count of its
    /// children — matches actual vim behavior.
    pub fn equalize_splits(&mut self) {
        self.rebalance_leaves();
    }

    /// Set the `ratio` of the `Split` reached by following `path` from the root
    /// (`false` = into `first`, `true` = into `second`). No-op if the path doesn't
    /// land on a `Split`. The ratio is clamped to 10..=90.
    pub fn set_ratio_at(&mut self, path: &[bool], ratio: u16) {
        let mut node = self;
        for &go_second in path {
            match node {
                Layout::Split { first, second, .. } => {
                    node = if go_second { second } else { first };
                }
                _ => return,
            }
        }
        if let Layout::Split { ratio: r, .. } = node {
            *r = ratio.clamp(10, 90);
        }
    }

    /// Swap any leaf references pointing at `a` with `b` and vice versa.
    /// Used after `app.panes.swap(a, b)` so layout leaves still point at
    /// the correct pane after the storage move. Walks the whole tree.
    pub fn swap_leaf_refs(&mut self, a: PaneId, b: PaneId) {
        if a == b {
            return;
        }
        match self {
            Layout::Empty => {}
            Layout::Leaf { active, tabs } => {
                let swap = |x: &mut PaneId| {
                    if *x == a {
                        *x = b;
                    } else if *x == b {
                        *x = a;
                    }
                };
                swap(active);
                for t in tabs.iter_mut() {
                    swap(t);
                }
            }
            Layout::Split { first, second, .. } => {
                first.swap_leaf_refs(a, b);
                second.swap_leaf_refs(a, b);
            }
        }
    }

    /// After `app.panes.remove(removed)`, every leaf id past `removed` shifts down
    /// by one. Leaves pointing AT `removed` become `Empty` (the pane is gone —
    /// keeping the id would silently re-bind the leaf to whatever pane shifted
    /// down to take that index). Splits with an `Empty` child collapse to the
    /// other branch so the tree stays well-formed for re-rendering.
    pub fn shift_after(&mut self, removed: PaneId) {
        match self {
            Layout::Empty => {}
            Layout::Leaf { active, tabs } => {
                // Drop any tab pointing AT `removed`; shift higher ids down.
                tabs.retain(|t| *t != removed);
                for t in tabs.iter_mut() {
                    if *t > removed {
                        *t -= 1;
                    }
                }
                if tabs.is_empty() {
                    *self = Layout::Empty;
                } else if *active == removed {
                    *active = tabs[0];
                } else if *active > removed {
                    *active -= 1;
                }
            }
            Layout::Split { first, second, .. } => {
                first.shift_after(removed);
                second.shift_after(removed);
                // Collapse splits whose child became Empty. Take the
                // surviving branch's contents in place to avoid a
                // mid-tree placeholder.
                let collapse = match (&**first, &**second) {
                    (Layout::Empty, Layout::Empty) => Some(Layout::Empty),
                    (Layout::Empty, _) => Some((**second).clone()),
                    (_, Layout::Empty) => Some((**first).clone()),
                    _ => None,
                };
                if let Some(replacement) = collapse {
                    *self = replacement;
                }
            }
        }
    }

    /// Compute each leaf's body rect inside `area`, allowing one cell per divider.
    /// Returns `(leaf_rects, divider_rects)`.
    pub fn compute_rects(&self, area: Rect) -> (Vec<(PaneId, Rect)>, Vec<DividerRect>) {
        let mut leaves = Vec::new();
        let mut divs = Vec::new();
        self.walk_rects(area, &mut leaves, &mut divs);
        (leaves, divs)
    }
    fn walk_rects(
        &self,
        area: Rect,
        leaves: &mut Vec<(PaneId, Rect)>,
        divs: &mut Vec<DividerRect>,
    ) {
        match self {
            Layout::Empty => {}
            Layout::Leaf { active, .. } => leaves.push((*active, area)),
            Layout::Split {
                dir,
                ratio,
                first,
                second,
            } => {
                let (a, divider, b) = split_rects(area, *dir, *ratio);
                if divider.width > 0 && divider.height > 0 {
                    divs.push((divider, *dir));
                }
                first.walk_rects(a, leaves, divs);
                second.walk_rects(b, leaves, divs);
            }
        }
    }
}

/// A split divider's screen rect plus its orientation.
pub type DividerRect = (Rect, SplitDir);

/// Everything the event loop needs to drag-resize one split: the divider's
/// screen rect, the split's orientation, the area the whole split occupies (so a
/// drag position maps to a ratio), and the path to that `Split` node from the
/// root (for [`Layout::set_ratio_at`]).
#[derive(Debug, Clone)]
pub struct DividerHit {
    pub rect: Rect,
    pub dir: SplitDir,
    pub area: Rect,
    pub path: Vec<bool>,
}

impl DividerHit {
    /// The ratio (10..=90) implied by a pointer at `(x, y)` within `self.area`.
    pub fn ratio_for(&self, x: u16, y: u16) -> u16 {
        let (pos, start, span) = match self.dir {
            SplitDir::Horizontal => (x, self.area.x, self.area.width),
            SplitDir::Vertical => (y, self.area.y, self.area.height),
        };
        if span == 0 {
            return 50;
        }
        let off = pos.saturating_sub(start) as u32;
        ((off * 100) / span as u32).clamp(10, 90) as u16
    }
}

impl Layout {
    /// 2026-07-25 — walk the tree and rewrite every split's ratio
    /// so all LEAVES render at equal size regardless of tree
    /// shape. For each `Split { first, second }` node, the ratio
    /// becomes `leaves(first) / (leaves(first) + leaves(second))`.
    ///
    /// Examples on a binary tree:
    ///   3 panes: `Split(a, Split(b, c))` → outer ratio = 1/3,
    ///     inner ratio = 1/2 → panes render at 33/33.5/33.5.
    ///   4 panes: two Splits with ratio 50/50 at each level → 25 each.
    ///   5 panes: mixed — the algorithm keeps each leaf's target
    ///     size proportional to 1/N regardless of tree shape.
    ///
    /// Returns the leaf count of this subtree (used internally
    /// during recursion; callers usually ignore it).
    pub fn rebalance_leaves(&mut self) -> usize {
        match self {
            Layout::Empty => 0,
            Layout::Leaf { .. } => 1,
            Layout::Split {
                ratio,
                first,
                second,
                ..
            } => {
                let n_first = first.rebalance_leaves();
                let n_second = second.rebalance_leaves();
                let total = n_first + n_second;
                if total > 0 {
                    let r = ((n_first as u32 * 100) / total as u32) as u16;
                    // Clamp so no leaf collapses to zero cells — the
                    // 10..=90 clamp in split_rects would clip anyway,
                    // but doing it here keeps the stored ratio and
                    // rendered ratio consistent.
                    *ratio = r.clamp(10, 90);
                }
                total
            }
        }
    }
}

/// Assemble `leaves` into a grid Layout matching one of a small
/// set of shapes:
///
/// - n=1 → leaves[0]
/// - n=2 → H-split (side by side, 50/50)
/// - n=3 → left leaf + right V-split (2 stacked on the right)
/// - n=4 → 2×2 grid
/// - n=5-6 → 3×2 grid (3 columns, 2 rows; last column may hold 1)
/// - n=7-8 → 4×2 grid
///
/// Panics on n>8 — callers should cap in advance
/// ([`Layout::spread_to_splits`] does).
fn build_grid(leaves: &[Layout], n: usize) -> Layout {
    assert!((1..=8).contains(&n), "build_grid n must be 1..=8, got {n}");
    let clone = |i: usize| leaves[i].clone();
    match n {
        1 => clone(0),
        2 => Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(clone(0)),
            second: Box::new(clone(1)),
        },
        3 => Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(clone(0)),
            second: Box::new(Layout::Split {
                dir: SplitDir::Vertical,
                ratio: 50,
                first: Box::new(clone(1)),
                second: Box::new(clone(2)),
            }),
        },
        4 => Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::Split {
                dir: SplitDir::Vertical,
                ratio: 50,
                first: Box::new(clone(0)),
                second: Box::new(clone(1)),
            }),
            second: Box::new(Layout::Split {
                dir: SplitDir::Vertical,
                ratio: 50,
                first: Box::new(clone(2)),
                second: Box::new(clone(3)),
            }),
        },
        5 | 6 => {
            // 3 columns; leftmost holds leaves 0-1, middle 2-3, right 4[-5].
            let col = |a: usize, b: Option<usize>| -> Layout {
                match b {
                    Some(i) => Layout::Split {
                        dir: SplitDir::Vertical,
                        ratio: 50,
                        first: Box::new(clone(a)),
                        second: Box::new(clone(i)),
                    },
                    None => clone(a),
                }
            };
            let c0 = col(0, Some(1));
            let c1 = col(2, Some(3));
            let c2 = if n == 6 {
                col(4, Some(5))
            } else {
                col(4, None)
            };
            // Horizontal cascade: c0 | (c1 | c2)
            Layout::Split {
                dir: SplitDir::Horizontal,
                ratio: 33,
                first: Box::new(c0),
                second: Box::new(Layout::Split {
                    dir: SplitDir::Horizontal,
                    ratio: 50,
                    first: Box::new(c1),
                    second: Box::new(c2),
                }),
            }
        }
        7 | 8 => {
            // 4 columns × 2 rows. Column i holds leaves 2i, 2i+1
            // (with the last column single when n=7).
            let col = |a: usize, b: Option<usize>| -> Layout {
                match b {
                    Some(i) => Layout::Split {
                        dir: SplitDir::Vertical,
                        ratio: 50,
                        first: Box::new(clone(a)),
                        second: Box::new(clone(i)),
                    },
                    None => clone(a),
                }
            };
            let c0 = col(0, Some(1));
            let c1 = col(2, Some(3));
            let c2 = col(4, Some(5));
            let c3 = if n == 8 {
                col(6, Some(7))
            } else {
                col(6, None)
            };
            // Cascade H-splits with balanced ratios: (c0 | c1) | (c2 | c3).
            Layout::Split {
                dir: SplitDir::Horizontal,
                ratio: 50,
                first: Box::new(Layout::Split {
                    dir: SplitDir::Horizontal,
                    ratio: 50,
                    first: Box::new(c0),
                    second: Box::new(c1),
                }),
                second: Box::new(Layout::Split {
                    dir: SplitDir::Horizontal,
                    ratio: 50,
                    first: Box::new(c2),
                    second: Box::new(c3),
                }),
            }
        }
        _ => unreachable!("caller must cap n at 8"),
    }
}

/// Carve `area` into `(first, divider, second)` for a split. The divider is one
/// cell on the split axis (omitted — zero-sized — if `area` is too small).
pub fn split_rects(area: Rect, dir: SplitDir, ratio: u16) -> (Rect, Rect, Rect) {
    let ratio = ratio.clamp(10, 90);
    match dir {
        SplitDir::Horizontal => {
            if area.width < 3 {
                return (
                    area,
                    Rect::new(area.x, area.y, 0, area.height),
                    Rect::new(area.x, area.y, 0, area.height),
                );
            }
            let usable = area.width - 1;
            let w1 = ((usable as u32 * ratio as u32) / 100).max(1) as u16;
            let w1 = w1.min(usable - 1);
            let a = Rect::new(area.x, area.y, w1, area.height);
            let d = Rect::new(area.x + w1, area.y, 1, area.height);
            let b = Rect::new(area.x + w1 + 1, area.y, usable - w1, area.height);
            (a, d, b)
        }
        SplitDir::Vertical => {
            if area.height < 3 {
                return (
                    area,
                    Rect::new(area.x, area.y, area.width, 0),
                    Rect::new(area.x, area.y, area.width, 0),
                );
            }
            let usable = area.height - 1;
            let h1 = ((usable as u32 * ratio as u32) / 100).max(1) as u16;
            let h1 = h1.min(usable - 1);
            let a = Rect::new(area.x, area.y, area.width, h1);
            let d = Rect::new(area.x, area.y + h1, area.width, 1);
            let b = Rect::new(area.x, area.y + h1 + 1, area.width, usable - h1);
            (a, d, b)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn leaf_basics() {
        let mut l = Layout::leaf(0);
        assert_eq!(l.leaves(), vec![0]);
        assert_eq!(l.first_leaf(), Some(0));
        assert!(l.contains(0));
        l.set_leaf_pane(0, 3);
        assert_eq!(l.leaves(), vec![3]);
    }

    #[test]
    fn split_and_collapse() {
        let mut l = Layout::leaf(0);
        // split leaf 0 → Split(Leaf 0, Leaf 1)
        assert!(l.replace_leaf(
            0,
            Layout::Split {
                dir: SplitDir::Horizontal,
                ratio: 50,
                first: Box::new(Layout::leaf(0)),
                second: Box::new(Layout::leaf(1)),
            }
        ));
        assert_eq!(l.leaves(), vec![0, 1]);
        // nested split of leaf 1 → Split(Leaf 0, Split(Leaf 1, Leaf 2))
        assert!(l.replace_leaf(
            1,
            Layout::Split {
                dir: SplitDir::Vertical,
                ratio: 50,
                first: Box::new(Layout::leaf(1)),
                second: Box::new(Layout::leaf(2)),
            }
        ));
        assert_eq!(l.leaves(), vec![0, 1, 2]);
        // remove leaf 1 → its sibling (Leaf 2) takes its place
        assert!(l.remove_leaf(1));
        assert_eq!(l.leaves(), vec![0, 2]);
        // remove leaf 0 → collapses to just Leaf 2
        assert!(l.remove_leaf(0));
        assert_eq!(l.leaves(), vec![2]);
        assert!(matches!(l, Layout::Leaf { active: 2, .. }));
        // remove the last → Empty
        assert!(l.remove_leaf(2));
        assert!(matches!(l, Layout::Empty));
    }

    #[test]
    fn shift_after_reindexes() {
        let mut l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf(0)),
            second: Box::new(Layout::Split {
                dir: SplitDir::Vertical,
                ratio: 50,
                first: Box::new(Layout::leaf(1)),
                second: Box::new(Layout::leaf(3)),
            }),
        };
        l.shift_after(2); // pretend pane 2 was removed from app.panes
        assert_eq!(l.leaves(), vec![0, 1, 2]);
    }

    #[test]
    fn shift_after_drops_leaf_at_removed_id() {
        // A leaf pointing at the removed pane id must become Empty
        // (don't silently re-bind to whatever pane shifted into its
        // slot). Splits collapse around the missing leaf.
        let mut l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf(0)),
            second: Box::new(Layout::leaf(1)),
        };
        l.shift_after(0);
        // Pane 0 removed: first leaf gone, second was Leaf(1) → Leaf(0).
        // Split collapses to that leaf.
        assert!(matches!(l, Layout::Leaf { active: 0, .. }));
    }

    #[test]
    fn shift_after_collapses_nested_splits() {
        // Removing both children of a nested split should propagate
        // the Empty up so the parent collapses too.
        let mut l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf(0)),
            second: Box::new(Layout::Split {
                dir: SplitDir::Vertical,
                ratio: 50,
                first: Box::new(Layout::leaf(1)),
                second: Box::new(Layout::leaf(2)),
            }),
        };
        l.shift_after(1);
        // After removing pane 1, the nested split's first child is
        // dropped; the inner split collapses to Leaf(1) (was Leaf 2,
        // shifted). The outer split survives with both leaves.
        assert_eq!(l.leaves(), vec![0, 1]);
    }

    #[test]
    fn swap_siblings_swaps_immediate_parent() {
        let mut l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf(0)),
            second: Box::new(Layout::leaf(1)),
        };
        let swapped = l.swap_siblings_containing(0);
        assert!(swapped);
        let Layout::Split { first, second, .. } = &l else {
            panic!()
        };
        assert!(matches!(**first, Layout::Leaf { active: 1, .. }));
        assert!(matches!(**second, Layout::Leaf { active: 0, .. }));
    }

    #[test]
    fn swap_siblings_walks_to_deepest_split() {
        // Outer split holds leaf 0 + an inner split holding leaves 1 + 2.
        // Asking to swap siblings of leaf 1 should swap inner's children
        // (leaves 1 + 2), not the outer.
        let mut l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf(0)),
            second: Box::new(Layout::Split {
                dir: SplitDir::Vertical,
                ratio: 50,
                first: Box::new(Layout::leaf(1)),
                second: Box::new(Layout::leaf(2)),
            }),
        };
        let swapped = l.swap_siblings_containing(1);
        assert!(swapped);
        let Layout::Split { second, .. } = &l else {
            panic!()
        };
        let Layout::Split {
            first: f,
            second: s,
            ..
        } = &**second
        else {
            panic!()
        };
        assert!(matches!(**f, Layout::Leaf { active: 2, .. }));
        assert!(matches!(**s, Layout::Leaf { active: 1, .. }));
    }

    #[test]
    fn adjust_split_grows_first_side_when_target_in_first() {
        let mut l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf(0)),
            second: Box::new(Layout::leaf(1)),
        };
        // Active leaf is 0 (in `first`). Grow by 10 ⇒ ratio rises.
        assert!(l.adjust_split_ratio_for(0, SplitDir::Horizontal, 10));
        let Layout::Split { ratio, .. } = &l else {
            panic!()
        };
        assert_eq!(*ratio, 60);
    }

    #[test]
    fn adjust_split_grows_second_side_when_target_in_second() {
        let mut l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf(0)),
            second: Box::new(Layout::leaf(1)),
        };
        // Active leaf is 1 (in `second`). Grow by 10 ⇒ ratio FALLS (so
        // `first` shrinks, `second` grows).
        assert!(l.adjust_split_ratio_for(1, SplitDir::Horizontal, 10));
        let Layout::Split { ratio, .. } = &l else {
            panic!()
        };
        assert_eq!(*ratio, 40);
    }

    #[test]
    fn adjust_split_skips_wrong_direction() {
        // Outer is Vertical (stacked); active leaf is 0 (top).
        // A "grow width" (Horizontal) should miss — no enclosing horizontal split.
        let mut l = Layout::Split {
            dir: SplitDir::Vertical,
            ratio: 50,
            first: Box::new(Layout::leaf(0)),
            second: Box::new(Layout::leaf(1)),
        };
        let res = l.adjust_split_ratio_for(0, SplitDir::Horizontal, 10);
        assert!(!res);
    }

    #[test]
    fn move_active_to_changes_dir_and_swaps() {
        // Vertical split (stacked: 0 on top, 1 on bottom). Move active 1
        // to the LEFT (target dir = Horizontal, to_second = false).
        // After: dir = Horizontal, first = 1, second = 0.
        let mut l = Layout::Split {
            dir: SplitDir::Vertical,
            ratio: 50,
            first: Box::new(Layout::leaf(0)),
            second: Box::new(Layout::leaf(1)),
        };
        let changed = l.move_active_to(1, SplitDir::Horizontal, false);
        assert!(changed);
        let Layout::Split {
            dir, first, second, ..
        } = &l
        else {
            panic!()
        };
        assert_eq!(*dir, SplitDir::Horizontal);
        assert!(matches!(**first, Layout::Leaf { active: 1, .. }));
        assert!(matches!(**second, Layout::Leaf { active: 0, .. }));
    }

    #[test]
    fn move_active_to_noop_when_already_correct() {
        // Horizontal: 0 left, 1 right. Move active 1 to the right ⇒ no-op.
        let mut l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf(0)),
            second: Box::new(Layout::leaf(1)),
        };
        let changed = l.move_active_to(1, SplitDir::Horizontal, true);
        assert!(!changed);
    }

    #[test]
    fn equalize_splits_resets_every_ratio() {
        let mut l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 75,
            first: Box::new(Layout::leaf(0)),
            second: Box::new(Layout::Split {
                dir: SplitDir::Vertical,
                ratio: 20,
                first: Box::new(Layout::leaf(1)),
                second: Box::new(Layout::leaf(2)),
            }),
        };
        l.equalize_splits();
        // 2026-07-25 — equalize now weights ratios by leaf count
        // (was: 50/50 at every level). For an unbalanced 3-leaf
        // tree `Split(Leaf, Split(Leaf, Leaf))` this means the
        // outer ratio becomes 33 (1 leaf : 2 leaves) and the
        // inner stays 50 (1 : 1). Result: all three panes render
        // at ~33% of the total area, which is what "equalize"
        // is supposed to mean.
        let Layout::Split { ratio, second, .. } = &l else {
            panic!()
        };
        assert_eq!(*ratio, 33);
        let Layout::Split { ratio: inner, .. } = &**second else {
            panic!()
        };
        assert_eq!(*inner, 50);
    }

    #[test]
    fn set_ratio_walks_the_path() {
        let mut l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf(0)),
            second: Box::new(Layout::Split {
                dir: SplitDir::Vertical,
                ratio: 50,
                first: Box::new(Layout::leaf(1)),
                second: Box::new(Layout::leaf(2)),
            }),
        };
        l.set_ratio_at(&[], 70); // the outer split
        l.set_ratio_at(&[true], 30); // the nested split (go into `second`)
        l.set_ratio_at(&[false], 99); // a Leaf — no-op
        let Layout::Split { ratio, second, .. } = &l else {
            panic!()
        };
        assert_eq!(*ratio, 70);
        let Layout::Split { ratio: inner, .. } = &**second else {
            panic!()
        };
        assert_eq!(*inner, 30);
    }

    #[test]
    fn leaf_containing_returns_tab_list_for_background_tab() {
        // A leaf with background tabs [10, 20, 30], active is 20.
        // leaf_containing(30) should return the full [10, 20, 30]
        // (not just the queried pane).
        let l = Layout::leaf_with_tabs(20, vec![10, 20, 30]);
        assert_eq!(l.leaf_containing(30), Some(&[10, 20, 30][..]));
        assert_eq!(l.leaf_containing(10), Some(&[10, 20, 30][..]));
        assert_eq!(l.leaf_containing(20), Some(&[10, 20, 30][..]));
        assert_eq!(l.leaf_containing(99), None);
    }

    #[test]
    fn leaf_containing_finds_across_splits() {
        let l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf_with_tabs(1, vec![1, 2])),
            second: Box::new(Layout::leaf_with_tabs(3, vec![3, 4])),
        };
        assert_eq!(l.leaf_containing(2), Some(&[1, 2][..]));
        assert_eq!(l.leaf_containing(4), Some(&[3, 4][..]));
        assert_eq!(l.leaf_containing(99), None);
    }

    #[test]
    fn all_panes_includes_background_tabs_across_splits() {
        // Regression check: `all_panes()` must surface background tabs on
        // BOTH sides of a split. This is what garbage-collection walks
        // rely on to know "pane X is still reachable somewhere".
        let l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf_with_tabs(1, vec![1, 2, 5])),
            second: Box::new(Layout::leaf_with_tabs(3, vec![3, 4])),
        };
        let mut panes = l.all_panes();
        panes.sort();
        assert_eq!(panes, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn remove_background_tab_keeps_leaf_and_active() {
        // Regression: removing a BACKGROUND tab must not touch `active`
        // and must not collapse the leaf.
        let mut l = Layout::leaf_with_tabs(20, vec![10, 20, 30]);
        assert!(l.remove_leaf(10));
        let Layout::Leaf { active, tabs } = &l else {
            panic!("leaf collapsed unexpectedly");
        };
        assert_eq!(*active, 20);
        assert_eq!(*tabs, vec![20, 30]);
    }

    #[test]
    fn divider_hit_ratio_for() {
        let area = Rect::new(10, 0, 100, 20);
        let h = DividerHit {
            rect: Rect::new(60, 0, 1, 20),
            dir: SplitDir::Horizontal,
            area,
            path: vec![],
        };
        assert_eq!(h.ratio_for(60, 5), 50); // 50 cols into a 100-wide area at x=10
        assert_eq!(h.ratio_for(10, 5), 10); // clamped low
        assert_eq!(h.ratio_for(109, 5), 90); // clamped high
    }

    #[test]
    fn find_leaf_pair_split_mut_matches_direct_hsplit() {
        let mut l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf(0)),
            second: Box::new(Layout::leaf(1)),
        };
        let hit = l.find_leaf_pair_split_mut(0, 1);
        assert!(hit.is_some());
        assert_eq!(hit.unwrap().1, SplitDir::Horizontal);
    }

    #[test]
    fn find_leaf_pair_split_mut_matches_swapped_order() {
        let mut l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf(7)),
            second: Box::new(Layout::leaf(3)),
        };
        assert!(l.find_leaf_pair_split_mut(3, 7).is_some());
    }

    #[test]
    fn find_leaf_pair_split_mut_rejects_multi_tab_leaf() {
        // A leaf with a second background tab isn't clean, so the
        // helper falls through to give the caller a chance to fall
        // back to the default behavior.
        let mut l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf_with_tabs(0, vec![0, 9])),
            second: Box::new(Layout::leaf(1)),
        };
        assert!(l.find_leaf_pair_split_mut(0, 1).is_none());
    }

    #[test]
    fn find_leaf_pair_split_mut_finds_nested_pair() {
        // {C1, C2} live under a nested split, alongside an editor.
        // Helper should walk into the nested split and match there.
        let mut l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 40,
            first: Box::new(Layout::leaf(99)), // editor
            second: Box::new(Layout::Split {
                dir: SplitDir::Horizontal,
                ratio: 50,
                first: Box::new(Layout::leaf(1)),
                second: Box::new(Layout::leaf(2)),
            }),
        };
        assert!(l.find_leaf_pair_split_mut(1, 2).is_some());
    }

    #[test]
    fn fill_first_empty_replaces_the_leftmost_empty_hole() {
        let mut l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::Empty),
            second: Box::new(Layout::Empty),
        };
        assert!(l.fill_first_empty(Layout::leaf(5)));
        match l {
            Layout::Split { first, second, .. } => {
                assert!(matches!(*first, Layout::Leaf { .. }));
                assert!(matches!(*second, Layout::Empty));
            }
            _ => panic!("split lost its shape"),
        }
    }

    #[test]
    fn fill_first_empty_reports_missing_hole() {
        let mut l = Layout::leaf(0);
        assert!(!l.fill_first_empty(Layout::leaf(1)));
    }

    #[test]
    fn contains_empty_walks_nested_splits() {
        let l = Layout::Split {
            dir: SplitDir::Vertical,
            ratio: 50,
            first: Box::new(Layout::leaf(0)),
            second: Box::new(Layout::Split {
                dir: SplitDir::Horizontal,
                ratio: 50,
                first: Box::new(Layout::leaf(1)),
                second: Box::new(Layout::Empty),
            }),
        };
        assert!(l.contains_empty());
    }

    #[test]
    fn find_pure_pane_cluster_mut_matches_exact_set() {
        // Whole tree is exactly {0, 1, 2, 3}.
        let mut l = Layout::Split {
            dir: SplitDir::Vertical,
            ratio: 50,
            first: Box::new(Layout::Split {
                dir: SplitDir::Horizontal,
                ratio: 50,
                first: Box::new(Layout::leaf(0)),
                second: Box::new(Layout::leaf(1)),
            }),
            second: Box::new(Layout::Split {
                dir: SplitDir::Horizontal,
                ratio: 50,
                first: Box::new(Layout::leaf(2)),
                second: Box::new(Layout::leaf(3)),
            }),
        };
        let set: std::collections::HashSet<PaneId> = [0, 1, 2, 3].into_iter().collect();
        assert!(l.find_pure_pane_cluster_mut(&set).is_some());
    }

    #[test]
    fn find_pure_pane_cluster_mut_returns_smallest_subtree() {
        // Editor on the left, {1, 2, 3, 4} 2×2 grid on the right.
        // Cluster of {1, 2, 3, 4} must be the RIGHT subtree, not
        // the whole tree.
        let mut l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 30,
            first: Box::new(Layout::leaf(99)), // editor
            second: Box::new(Layout::Split {
                dir: SplitDir::Vertical,
                ratio: 50,
                first: Box::new(Layout::Split {
                    dir: SplitDir::Horizontal,
                    ratio: 50,
                    first: Box::new(Layout::leaf(1)),
                    second: Box::new(Layout::leaf(2)),
                }),
                second: Box::new(Layout::Split {
                    dir: SplitDir::Horizontal,
                    ratio: 50,
                    first: Box::new(Layout::leaf(3)),
                    second: Box::new(Layout::leaf(4)),
                }),
            }),
        };
        let set: std::collections::HashSet<PaneId> = [1, 2, 3, 4].into_iter().collect();
        let hit = l.find_pure_pane_cluster_mut(&set).unwrap();
        // The cluster should have exactly 4 leaves — the 2×2.
        assert_eq!(hit.all_panes().len(), 4);
    }

    #[test]
    fn find_pure_pane_cluster_mut_rejects_mixed_leaves() {
        // Set {0, 1} but the tree also has an editor (99) at the
        // same level. There's no subtree with only {0, 1}.
        let mut l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf(99)),
            second: Box::new(Layout::Split {
                dir: SplitDir::Horizontal,
                ratio: 50,
                first: Box::new(Layout::leaf(0)),
                second: Box::new(Layout::leaf(1)),
            }),
        };
        // {99, 0, 1} matches the whole tree → wrong set for the
        // Claude case. Passing {0, 1} finds the inner split.
        let set: std::collections::HashSet<PaneId> = [0, 1].into_iter().collect();
        let hit = l.find_pure_pane_cluster_mut(&set).unwrap();
        assert_eq!(hit.all_panes().len(), 2);
    }

    #[test]
    fn merge_to_tabs_flattens_split_tree_into_one_leaf() {
        // 3-way split (H(0, V(1, 2))) should collapse to a leaf with
        // [0, 1, 2] tabs, keeping active on 1 (the hint).
        let l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf(0)),
            second: Box::new(Layout::Split {
                dir: SplitDir::Vertical,
                ratio: 50,
                first: Box::new(Layout::leaf(1)),
                second: Box::new(Layout::leaf(2)),
            }),
        };
        let merged = l.merge_to_tabs(1);
        let Layout::Leaf { active, tabs } = merged else {
            panic!("expected leaf")
        };
        assert_eq!(active, 1);
        assert_eq!(tabs, vec![0, 1, 2]);
    }

    #[test]
    fn merge_to_tabs_preserves_background_tabs_from_every_leaf() {
        // Each side has multiple tabs — they must all survive.
        let l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf_with_tabs(1, vec![0, 1, 2])),
            second: Box::new(Layout::leaf_with_tabs(4, vec![3, 4, 5])),
        };
        let merged = l.merge_to_tabs(4);
        let Layout::Leaf { active, tabs } = merged else {
            panic!()
        };
        assert_eq!(active, 4);
        assert_eq!(tabs, vec![0, 1, 2, 3, 4, 5]);
    }

    #[test]
    fn merge_to_tabs_falls_back_to_first_when_hint_missing() {
        let l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf(0)),
            second: Box::new(Layout::leaf(1)),
        };
        let merged = l.merge_to_tabs(99);
        let Layout::Leaf { active, .. } = merged else {
            panic!()
        };
        assert_eq!(active, 0);
    }

    #[test]
    fn merge_to_tabs_on_single_leaf_is_idempotent() {
        let l = Layout::leaf_with_tabs(2, vec![1, 2, 3]);
        let merged = l.merge_to_tabs(2);
        let Layout::Leaf { active, tabs } = merged else {
            panic!()
        };
        assert_eq!(active, 2);
        assert_eq!(tabs, vec![1, 2, 3]);
    }

    #[test]
    fn merge_to_tabs_on_empty_stays_empty() {
        assert!(matches!(Layout::Empty.merge_to_tabs(0), Layout::Empty));
    }

    #[test]
    fn spread_to_splits_pair_produces_horizontal_split() {
        let l = Layout::leaf_with_tabs(0, vec![0, 1]);
        let spread = l.spread_to_splits();
        let Layout::Split {
            dir, first, second, ..
        } = spread
        else {
            panic!("expected 2-way split")
        };
        assert_eq!(dir, SplitDir::Horizontal);
        assert!(matches!(*first, Layout::Leaf { active: 0, .. }));
        assert!(matches!(*second, Layout::Leaf { active: 1, .. }));
    }

    #[test]
    fn spread_to_splits_single_tab_is_noop() {
        let l = Layout::leaf(0);
        let spread = l.spread_to_splits();
        assert!(matches!(spread, Layout::Leaf { active: 0, .. }));
    }

    #[test]
    fn spread_to_splits_ignores_already_split_layout() {
        let l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf(0)),
            second: Box::new(Layout::leaf(1)),
        };
        let spread = l.spread_to_splits();
        // Unchanged shape.
        assert!(matches!(spread, Layout::Split { .. }));
        assert_eq!(spread.all_panes(), vec![0, 1]);
    }

    #[test]
    fn spread_to_splits_beyond_8_stacks_remainder_as_tabs() {
        // 10 tabs → 8 slots; slot 8 (the last) hosts tabs [7, 8, 9].
        let l = Layout::leaf_with_tabs(0, (0..10).collect());
        let spread = l.spread_to_splits();
        let leaves_of_layout = |lay: &Layout| lay.leaves();
        assert_eq!(leaves_of_layout(&spread).len(), 8);
        assert_eq!(spread.all_panes().len(), 10);
    }

    #[test]
    fn merge_then_spread_round_trips_pane_set() {
        // Start from a mixed split with background tabs, merge to
        // tabs, spread back to splits — the pane set stays the same.
        let l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf_with_tabs(1, vec![0, 1])),
            second: Box::new(Layout::leaf_with_tabs(2, vec![2, 3])),
        };
        let before = l.all_panes();
        let merged = l.merge_to_tabs(1);
        let spread = merged.spread_to_splits();
        assert_eq!(spread.all_panes(), before);
    }

    #[test]
    fn rects_sum_and_divide() {
        let area = Rect::new(0, 0, 80, 24);
        let l = Layout::Split {
            dir: SplitDir::Horizontal,
            ratio: 50,
            first: Box::new(Layout::leaf(0)),
            second: Box::new(Layout::leaf(1)),
        };
        let (leaves, divs) = l.compute_rects(area);
        assert_eq!(leaves.len(), 2);
        assert_eq!(divs.len(), 1);
        let (_, r0) = leaves[0];
        let (_, r1) = leaves[1];
        // widths + 1 divider == 80
        assert_eq!(r0.width + 1 + r1.width, 80);
        assert_eq!(r0.height, 24);
        assert_eq!(divs[0].0.width, 1);
    }
}