Guide API
Skip to main content

tvision_rs/widgets/splitter/
layout.rs

1//! Pure layout math for the splitter: constraint types + the flexbox solver.
2//! No view, no rendering — fully unit-testable.
3
4/// Which axis a [`Splitter`](super::Splitter) divides.
5#[derive(Clone, Copy, PartialEq, Eq, Debug)]
6pub enum Orientation {
7    /// Side-by-side panes, **vertical** dividers, split along **x** (`cols`).
8    Cols,
9    /// Stacked panes, **horizontal** dividers, split along **y** (`rows`).
10    Rows,
11}
12
13/// How a pane claims space along the splitter axis. `min == max` ⇒ a fixed pane.
14#[derive(Clone, Copy, PartialEq, Eq, Debug)]
15pub struct Constraints {
16    /// Share of *free* space (after every pane has its `min`). Authoring unit.
17    pub weight: u16,
18    /// Hard minimum size in cells along the axis.
19    pub min: i32,
20    /// Hard maximum size in cells along the axis.
21    pub max: i32,
22}
23
24impl Constraints {
25    /// Fully elastic: weight 1, `min 0`, `max i32::MAX`.
26    pub fn flex() -> Self {
27        Constraints {
28            weight: 1,
29            min: 0,
30            max: i32::MAX,
31        }
32    }
33    /// Elastic with a custom weight.
34    pub fn weight(w: u16) -> Self {
35        Constraints {
36            weight: w.max(1),
37            min: 0,
38            max: i32::MAX,
39        }
40    }
41    /// Pinned to exactly `n` cells (`min == max == n`).
42    pub fn fixed(n: i32) -> Self {
43        Constraints {
44            weight: 1,
45            min: n,
46            max: n,
47        }
48    }
49    /// Builder: set the minimum.
50    pub fn min(mut self, n: i32) -> Self {
51        self.min = n;
52        self
53    }
54    /// Builder: set the maximum.
55    pub fn max(mut self, n: i32) -> Self {
56        self.max = n;
57        self
58    }
59    /// A fixed pane has no free-space share.
60    pub fn is_fixed(&self) -> bool {
61        self.min == self.max
62    }
63}
64
65/// One pane's solver input: its hard bounds plus a mutable *effective weight*
66/// (seeded from `Constraints.weight`, mutated by drags/relax). Fixed panes
67/// (`min == max`) carry weight 0 and take no free space.
68#[derive(Clone, Copy, Debug)]
69pub struct Slot {
70    pub min: i32,
71    pub max: i32,
72    pub weight: f64,
73}
74
75impl Slot {
76    pub fn from_constraints(c: Constraints) -> Self {
77        Slot {
78            min: c.min,
79            max: c.max,
80            weight: if c.is_fixed() {
81                0.0
82            } else {
83                c.weight.max(1) as f64
84            },
85        }
86    }
87    #[allow(dead_code)]
88    fn is_fixed(&self) -> bool {
89        self.min == self.max
90    }
91}
92
93/// Apportion `total` cells across `slots`, honoring each `[min, max]` and
94/// distributing the remaining free space by `weight`. Deterministic
95/// (largest-remainder rounding); the returned sizes always sum to
96/// `total.max(sum_of_mins-clamped)` and never violate a slot's bounds.
97///
98/// `total` here is the **content** length (axis length already minus the
99/// dividers' reserved cells — the caller subtracts those).
100pub fn solve(slots: &[Slot], total: i32) -> Vec<i32> {
101    if slots.is_empty() {
102        return Vec::new();
103    }
104    // 1. Everyone starts at their min.
105    let mut sizes: Vec<i32> = slots.iter().map(|s| s.min).collect();
106    let used: i32 = sizes.iter().sum();
107    let mut free = total - used;
108
109    if free <= 0 {
110        // Not enough room even for the mins: shrink proportionally to mins,
111        // largest-remainder, never below 0. (Degenerate small-terminal case.)
112        return shrink_to_fit(&sizes, total.max(0));
113    }
114
115    // 2. Iteratively hand free space to non-saturated, weighted slots.
116    //    A slot is "open" if weight > 0 and size < max.
117    loop {
118        let open: Vec<usize> = (0..slots.len())
119            .filter(|&i| slots[i].weight > 0.0 && sizes[i] < slots[i].max)
120            .collect();
121        let wsum: f64 = open.iter().map(|&i| slots[i].weight).sum();
122        if open.is_empty() || wsum == 0.0 || free == 0 {
123            break;
124        }
125        // Ideal real allocation per open slot this round.
126        let mut alloc: Vec<(usize, i32, f64)> = open
127            .iter()
128            .map(|&i| {
129                let ideal = free as f64 * slots[i].weight / wsum;
130                let floor = ideal.floor() as i32;
131                // Clamp to headroom so we never exceed max in one shot.
132                let headroom = slots[i].max - sizes[i];
133                let give = floor.min(headroom);
134                (i, give, ideal - give as f64)
135            })
136            .collect();
137        let mut given: i32 = alloc.iter().map(|(_, g, _)| *g).sum();
138        // Largest-remainder: hand out the leftover cells one-by-one to the
139        // open slots with the biggest fractional remainder and remaining headroom.
140        let mut leftover = free - given;
141        alloc.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap());
142        let mut idx = 0;
143        while leftover > 0 && !alloc.is_empty() {
144            let len = alloc.len();
145            let (i, ref mut g, _) = alloc[idx % len];
146            if sizes[i] + *g < slots[i].max {
147                *g += 1;
148                given += 1;
149                leftover -= 1;
150            }
151            idx += 1;
152            // Safety: if a full sweep gave nothing, everyone is saturated.
153            if idx > len * 2 && leftover == free - given {
154                break;
155            }
156        }
157        for (i, g, _) in &alloc {
158            sizes[*i] += *g;
159        }
160        let progressed = given > 0;
161        free -= given;
162        if !progressed {
163            break;
164        }
165    }
166    sizes
167}
168
169/// Degenerate path: even the mins don't fit. Shrink proportionally to the mins.
170fn shrink_to_fit(mins: &[i32], total: i32) -> Vec<i32> {
171    let sum: i32 = mins.iter().sum();
172    if sum <= 0 {
173        return vec![0; mins.len()];
174    }
175    let mut sizes: Vec<i32> = mins
176        .iter()
177        .map(|&m| (m as i64 * total as i64 / sum as i64) as i32)
178        .collect();
179    // Largest-remainder fix so they sum to `total`.
180    let mut deficit = total - sizes.iter().sum::<i32>();
181    let mut order: Vec<usize> = (0..mins.len()).collect();
182    order.sort_by(|&a, &b| mins[b].cmp(&mins[a]));
183    let mut k = 0;
184    while deficit > 0 && !order.is_empty() {
185        sizes[order[k % order.len()]] += 1;
186        deficit -= 1;
187        k += 1;
188    }
189    sizes
190}
191
192/// The closed form for [`Splitter::relax`](super::Splitter::relax): the weight to
193/// give a pane currently sized `pane_size` so that making it flexible does not
194/// move any divider. `other_weights` = sum of the *currently flexible* panes'
195/// weights; `free_space` = current free cells (total content minus the sum of
196/// mins). Returns the weight; if `free_space <= 0` falls back to `1.0`.
197pub fn relax_weight(other_weights: f64, pane_size: i32, free_space: i32) -> f64 {
198    if free_space <= 0 || pane_size <= 0 {
199        return 1.0;
200    }
201    (other_weights * pane_size as f64 / free_space as f64).max(0.000_001)
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    fn slots(cs: &[Constraints]) -> Vec<Slot> {
209        cs.iter().map(|&c| Slot::from_constraints(c)).collect()
210    }
211
212    #[test]
213    fn three_equal_columns() {
214        let s = slots(&[
215            Constraints::flex(),
216            Constraints::flex(),
217            Constraints::flex(),
218        ]);
219        // 30 content cells, 3 equal panes.
220        assert_eq!(solve(&s, 30), vec![10, 10, 10]);
221    }
222
223    #[test]
224    fn equal_columns_largest_remainder_is_deterministic() {
225        let s = slots(&[
226            Constraints::flex(),
227            Constraints::flex(),
228            Constraints::flex(),
229        ]);
230        // 31 doesn't divide by 3: extras go to earliest slots, total == 31.
231        let out = solve(&s, 31);
232        assert_eq!(out.iter().sum::<i32>(), 31);
233        assert_eq!(out, vec![11, 10, 10]);
234    }
235
236    #[test]
237    fn fixed_sidebar_keeps_width_others_take_rest() {
238        let s = slots(&[
239            Constraints::fixed(20),
240            Constraints::flex(),
241            Constraints::weight(2),
242        ]);
243        // 20 fixed + (80 free split 1:2) => 20, ~27, ~53; sum == 100.
244        let out = solve(&s, 100);
245        assert_eq!(out[0], 20);
246        assert_eq!(out.iter().sum::<i32>(), 100);
247        assert!(out[2] > out[1], "weight-2 pane is wider");
248    }
249
250    #[test]
251    fn weight_one_respects_min() {
252        let s = slots(&[Constraints::flex().min(10), Constraints::flex()]);
253        // Total 12: pane0 floored at min 10, pane1 gets the rest (but min 0).
254        // free after mins = 12-10 = 2, split by weight 1:1 => pane0 11, pane1 1.
255        let out = solve(&s, 12);
256        assert!(out[0] >= 10);
257        assert_eq!(out.iter().sum::<i32>(), 12);
258    }
259
260    #[test]
261    fn max_saturates_and_redistributes() {
262        let s = slots(&[Constraints::flex().max(15), Constraints::flex()]);
263        // 100 cells: pane0 capped at 15, pane1 absorbs the remaining 85.
264        assert_eq!(solve(&s, 100), vec![15, 85]);
265    }
266
267    #[test]
268    fn relax_weight_preserves_position() {
269        // pane currently 20 cells, other flexible weights sum 3, free space 80.
270        let w = relax_weight(3.0, 20, 80);
271        assert!((w - 0.75).abs() < 1e-9);
272    }
273}