Skip to main content

termden_core/
layout.rs

1use serde::{Deserialize, Serialize};
2
3use crate::model::HarnessId;
4
5/// Split direction. `Horizontal` places children side by side (a vertical
6/// divider); `Vertical` stacks them.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
8#[serde(rename_all = "kebab-case")]
9pub enum Axis {
10    Horizontal,
11    Vertical,
12}
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum DropZone {
16    Left,
17    Right,
18    Top,
19    Bottom,
20    Center,
21}
22
23impl DropZone {
24    pub fn is_center(self) -> bool {
25        matches!(self, DropZone::Center)
26    }
27}
28
29/// Binary dwindle tree. Leaves reference harnesses that live in the same
30/// workspace; the tree only describes geometry.
31#[derive(Debug, Clone, Serialize, Deserialize)]
32#[serde(rename_all = "kebab-case")]
33pub enum LayoutNode {
34    Leaf(HarnessId),
35    Split {
36        axis: Axis,
37        /// Share of the available space given to `first`, between 0.1 and 0.9.
38        ratio: f32,
39        first: Box<LayoutNode>,
40        second: Box<LayoutNode>,
41    },
42}
43
44impl LayoutNode {
45    pub fn leaf(id: HarnessId) -> Self {
46        Self::Leaf(id)
47    }
48
49    pub fn split(axis: Axis, ratio: f32, first: LayoutNode, second: LayoutNode) -> Self {
50        Self::Split {
51            axis,
52            ratio: ratio.clamp(0.1, 0.9),
53            first: Box::new(first),
54            second: Box::new(second),
55        }
56    }
57
58    pub fn leaves(&self) -> Vec<HarnessId> {
59        let mut out = Vec::new();
60        self.collect_leaves(&mut out);
61        out
62    }
63
64    fn collect_leaves(&self, out: &mut Vec<HarnessId>) {
65        match self {
66            LayoutNode::Leaf(id) => out.push(*id),
67            LayoutNode::Split { first, second, .. } => {
68                first.collect_leaves(out);
69                second.collect_leaves(out);
70            }
71        }
72    }
73
74    pub fn len(&self) -> usize {
75        match self {
76            LayoutNode::Leaf(_) => 1,
77            LayoutNode::Split { first, second, .. } => first.len() + second.len(),
78        }
79    }
80
81    pub fn is_empty(&self) -> bool {
82        false
83    }
84
85    pub fn contains(&self, id: HarnessId) -> bool {
86        match self {
87            LayoutNode::Leaf(leaf) => *leaf == id,
88            LayoutNode::Split { first, second, .. } => first.contains(id) || second.contains(id),
89        }
90    }
91
92    pub fn first_leaf(&self) -> Option<HarnessId> {
93        match self {
94            LayoutNode::Leaf(id) => Some(*id),
95            LayoutNode::Split { first, .. } => first.first_leaf(),
96        }
97    }
98
99    /// Insert `new` next to `target`, splitting in the requested direction.
100    pub fn split_at(&mut self, target: HarnessId, new: HarnessId, zone: DropZone) -> bool {
101        if zone.is_center() {
102            return false;
103        }
104
105        match self {
106            LayoutNode::Leaf(id) if *id == target => {
107                let old = self.clone();
108                *self = match zone {
109                    DropZone::Left => Self::split(Axis::Horizontal, 0.5, Self::leaf(new), old),
110                    DropZone::Right => Self::split(Axis::Horizontal, 0.5, old, Self::leaf(new)),
111                    DropZone::Top => Self::split(Axis::Vertical, 0.5, Self::leaf(new), old),
112                    DropZone::Bottom => Self::split(Axis::Vertical, 0.5, old, Self::leaf(new)),
113                    DropZone::Center => unreachable!(),
114                };
115                true
116            }
117            LayoutNode::Leaf(_) => false,
118            LayoutNode::Split { first, second, .. } => {
119                first.split_at(target, new, zone) || second.split_at(target, new, zone)
120            }
121        }
122    }
123
124    /// Give `leaf` the share `share` of the split it sits directly in.
125    pub fn set_share(&mut self, leaf: HarnessId, share: f32) {
126        if let LayoutNode::Split {
127            ratio,
128            first,
129            second,
130            ..
131        } = self
132        {
133            if matches!(**first, LayoutNode::Leaf(id) if id == leaf) {
134                *ratio = share.clamp(0.1, 0.9);
135            } else if matches!(**second, LayoutNode::Leaf(id) if id == leaf) {
136                *ratio = (1.0 - share).clamp(0.1, 0.9);
137            } else {
138                first.set_share(leaf, share);
139                second.set_share(leaf, share);
140            }
141        }
142    }
143
144    /// Swap two leaves in place. Used for the center drop zone.
145    pub fn swap(&mut self, a: HarnessId, b: HarnessId) -> bool {
146        if a == b {
147            return false;
148        }
149
150        let mut found_a = false;
151        let mut found_b = false;
152        self.for_each_leaf_mut(&mut |id| {
153            if *id == a {
154                *id = b;
155                found_a = true;
156            } else if *id == b {
157                *id = a;
158                found_b = true;
159            }
160        });
161        found_a && found_b
162    }
163
164    fn for_each_leaf_mut(&mut self, f: &mut impl FnMut(&mut HarnessId)) {
165        match self {
166            LayoutNode::Leaf(id) => f(id),
167            LayoutNode::Split { first, second, .. } => {
168                first.for_each_leaf_mut(f);
169                second.for_each_leaf_mut(f);
170            }
171        }
172    }
173
174    /// Remove a leaf, collapsing its parent split. Returns false for the root
175    /// leaf; callers should keep at least one leaf alive.
176    pub fn remove(&mut self, id: HarnessId) -> bool {
177        let replacement = match self {
178            LayoutNode::Leaf(_) => return false,
179            LayoutNode::Split { first, second, .. } => {
180                if matches!(first.as_ref(), LayoutNode::Leaf(leaf) if *leaf == id) {
181                    Some((**second).clone())
182                } else if matches!(second.as_ref(), LayoutNode::Leaf(leaf) if *leaf == id) {
183                    Some((**first).clone())
184                } else if first.remove(id) || second.remove(id) {
185                    return true;
186                } else {
187                    None
188                }
189            }
190        };
191
192        match replacement {
193            Some(node) => {
194                *self = node;
195                true
196            }
197            None => false,
198        }
199    }
200
201    /// Set the ratio of the split at `path` (`false` = first child,
202    /// `true` = second, from the root). Returns false if there is none.
203    pub fn set_ratio(&mut self, path: &[bool], value: f32) -> bool {
204        match (self, path) {
205            (LayoutNode::Split { ratio, .. }, []) => {
206                *ratio = value.clamp(0.1, 0.9);
207                true
208            }
209            (LayoutNode::Split { first, second, .. }, [side, rest @ ..]) => {
210                if *side { second } else { first }.set_ratio(rest, value)
211            }
212            (LayoutNode::Leaf(_), _) => false,
213        }
214    }
215
216    /// Remove `dragged` and re-insert it relative to `target`.
217    pub fn move_leaf(&mut self, dragged: HarnessId, target: HarnessId, zone: DropZone) -> bool {
218        if dragged == target {
219            return false;
220        }
221        if self.len() < 2 || !self.contains(target) {
222            return false;
223        }
224
225        if zone.is_center() {
226            return self.swap(dragged, target);
227        }
228
229        self.remove(dragged);
230        if !self.contains(target) {
231            return false;
232        }
233        self.split_at(target, dragged, zone)
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240
241    #[test]
242    fn set_ratio_follows_path() {
243        let id = HarnessId::new;
244        let inner = LayoutNode::split(
245            Axis::Vertical,
246            0.5,
247            LayoutNode::leaf(id(2)),
248            LayoutNode::leaf(id(3)),
249        );
250        let mut root = LayoutNode::split(Axis::Horizontal, 0.5, LayoutNode::leaf(id(1)), inner);
251        assert!(root.set_ratio(&[true], 0.3));
252        assert!(root.set_ratio(&[], 2.0));
253        assert!(!root.set_ratio(&[false], 0.4));
254        let LayoutNode::Split { ratio, second, .. } = &root else {
255            panic!()
256        };
257        assert_eq!(*ratio, 0.9);
258        assert!(matches!(**second, LayoutNode::Split { ratio, .. } if ratio == 0.3));
259    }
260}