Skip to main content

mkapk_core/
layout.rs

1use alloc::collections::BTreeMap;
2use alloc::vec::Vec;
3
4use crate::{Insetsf, LayoutConstraints, Pointf, Sizef, Tree, WidgetId};
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
7pub enum LayoutDirection {
8    #[default]
9    Column,
10    Row,
11}
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14pub enum Alignment {
15    #[default]
16    Start,
17    Center,
18    End,
19    Stretch,
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Default)]
23pub struct LayoutBox {
24    pub id: WidgetId,
25    pub origin: Pointf,
26    pub size: Sizef,
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Default)]
30pub struct LayoutNode {
31    pub id: WidgetId,
32    pub direction: LayoutDirection,
33    pub constraints: LayoutConstraints,
34    pub margin: Insetsf,
35    pub padding: Insetsf,
36    pub flex_grow: f32,
37    pub alignment: Alignment,
38    pub preferred_size: Option<Sizef>,
39}
40
41#[derive(Debug, Clone, PartialEq, Default)]
42pub struct LayoutEngine {
43    nodes: BTreeMap<WidgetId, LayoutNode>,
44}
45
46#[derive(Debug, Clone, PartialEq, Default)]
47pub struct LayoutResult {
48    boxes: BTreeMap<WidgetId, LayoutBox>,
49}
50
51impl LayoutEngine {
52    pub fn new() -> Self {
53        Self {
54            nodes: BTreeMap::new(),
55        }
56    }
57
58    pub fn set_node(&mut self, node: LayoutNode) -> &mut Self {
59        self.nodes.insert(node.id, node);
60        self
61    }
62
63    pub fn node(&self, id: WidgetId) -> Option<&LayoutNode> {
64        self.nodes.get(&id)
65    }
66
67    pub fn compute(&mut self, tree: &Tree, root_constraints: LayoutConstraints) -> LayoutResult {
68        let mut measured = BTreeMap::new();
69        let mut result = LayoutResult::default();
70
71        if let Some(root) = tree.root() {
72            self.measure(root, tree, root_constraints, &mut measured);
73            let root_measured = *measured.get(&root).unwrap_or(&Sizef::default());
74            let root_node = self.nodes.get(&root).copied().unwrap_or_default();
75            let root_size = clamp_size(
76                root_measured,
77                intersect_constraints(root_constraints, root_node.constraints),
78            );
79            self.arrange_node(
80                root,
81                tree,
82                &measured,
83                Pointf::zero(),
84                root_size,
85                &mut result,
86            );
87        }
88
89        result
90    }
91
92    fn measure(
93        &self,
94        id: WidgetId,
95        tree: &Tree,
96        constraints: LayoutConstraints,
97        measured: &mut BTreeMap<WidgetId, Sizef>,
98    ) {
99        let node = self.nodes.get(&id).copied().unwrap_or_default();
100        let effective = intersect_constraints(constraints, node.constraints);
101
102        let widget_size = tree
103            .find(id)
104            .map(|n| n.widget.borrow().layout(effective))
105            .unwrap_or_default();
106        let size = clamp_size(node.preferred_size.unwrap_or(widget_size), effective);
107        measured.insert(id, size);
108
109        for &child in tree.children_of(id) {
110            let child_node = self.nodes.get(&child).copied().unwrap_or_default();
111            let child_constraints =
112                derive_child_constraints(node.direction, size, node.padding, child_node.margin);
113            self.measure(child, tree, child_constraints, measured);
114        }
115    }
116
117    fn arrange_node(
118        &self,
119        id: WidgetId,
120        tree: &Tree,
121        measured: &BTreeMap<WidgetId, Sizef>,
122        origin: Pointf,
123        allocated_size: Sizef,
124        result: &mut LayoutResult,
125    ) {
126        let node = self.nodes.get(&id).copied().unwrap_or_default();
127        let final_size = clamp_size(allocated_size, node.constraints);
128        result.boxes.insert(
129            id,
130            LayoutBox {
131                id,
132                origin,
133                size: final_size,
134            },
135        );
136
137        let content_origin = Pointf::new(origin.x + node.padding.left, origin.y + node.padding.top);
138        let content_size = Sizef::new(
139            (final_size.width - node.padding.horizontal()).max(0.0),
140            (final_size.height - node.padding.vertical()).max(0.0),
141        );
142
143        let children: Vec<WidgetId> = tree.children_of(id).to_vec();
144        match node.direction {
145            LayoutDirection::Row => {
146                self.arrange_row(
147                    &children,
148                    tree,
149                    measured,
150                    content_origin,
151                    content_size,
152                    result,
153                );
154            }
155            LayoutDirection::Column => {
156                self.arrange_column(
157                    &children,
158                    tree,
159                    measured,
160                    content_origin,
161                    content_size,
162                    result,
163                );
164            }
165        }
166    }
167
168    fn arrange_row(
169        &self,
170        children: &[WidgetId],
171        tree: &Tree,
172        measured: &BTreeMap<WidgetId, Sizef>,
173        content_origin: Pointf,
174        content_size: Sizef,
175        result: &mut LayoutResult,
176    ) {
177        let available_main = content_size.width;
178        let mut total_main = 0.0;
179        let mut total_flex = 0.0;
180        let mut infos = Vec::with_capacity(children.len());
181
182        for &child in children {
183            let node = self.nodes.get(&child).copied().unwrap_or_default();
184            let measured_size = *measured.get(&child).unwrap_or(&Sizef::default());
185            total_main += measured_size.width + node.margin.horizontal();
186            total_flex += node.flex_grow;
187            infos.push((child, node, measured_size));
188        }
189
190        let remaining = (available_main - total_main).max(0.0);
191        let mut x = content_origin.x;
192
193        for (child, node, measured_size) in infos {
194            let allocated_width = if total_flex > 0.0 && node.flex_grow > 0.0 {
195                measured_size.width + remaining * (node.flex_grow / total_flex)
196            } else {
197                measured_size.width
198            };
199
200            let available_cross = (content_size.height - node.margin.vertical()).max(0.0);
201            let allocated_height = match node.alignment {
202                Alignment::Stretch => available_cross,
203                _ => measured_size.height.min(available_cross),
204            };
205
206            let y_offset = match node.alignment {
207                Alignment::Start => 0.0,
208                Alignment::Center => (available_cross - allocated_height) / 2.0,
209                Alignment::End => available_cross - allocated_height,
210                Alignment::Stretch => 0.0,
211            };
212
213            let child_origin = Pointf::new(
214                x + node.margin.left,
215                content_origin.y + node.margin.top + y_offset,
216            );
217            let child_size = Sizef::new(allocated_width, allocated_height);
218
219            self.arrange_node(child, tree, measured, child_origin, child_size, result);
220
221            x += allocated_width + node.margin.horizontal();
222        }
223    }
224
225    fn arrange_column(
226        &self,
227        children: &[WidgetId],
228        tree: &Tree,
229        measured: &BTreeMap<WidgetId, Sizef>,
230        content_origin: Pointf,
231        content_size: Sizef,
232        result: &mut LayoutResult,
233    ) {
234        let available_main = content_size.height;
235        let mut total_main = 0.0;
236        let mut total_flex = 0.0;
237        let mut infos = Vec::with_capacity(children.len());
238
239        for &child in children {
240            let node = self.nodes.get(&child).copied().unwrap_or_default();
241            let measured_size = *measured.get(&child).unwrap_or(&Sizef::default());
242            total_main += measured_size.height + node.margin.vertical();
243            total_flex += node.flex_grow;
244            infos.push((child, node, measured_size));
245        }
246
247        let remaining = (available_main - total_main).max(0.0);
248        let mut y = content_origin.y;
249
250        for (child, node, measured_size) in infos {
251            let allocated_height = if total_flex > 0.0 && node.flex_grow > 0.0 {
252                measured_size.height + remaining * (node.flex_grow / total_flex)
253            } else {
254                measured_size.height
255            };
256
257            let available_cross = (content_size.width - node.margin.horizontal()).max(0.0);
258            let allocated_width = match node.alignment {
259                Alignment::Stretch => available_cross,
260                _ => measured_size.width.min(available_cross),
261            };
262
263            let x_offset = match node.alignment {
264                Alignment::Start => 0.0,
265                Alignment::Center => (available_cross - allocated_width) / 2.0,
266                Alignment::End => available_cross - allocated_width,
267                Alignment::Stretch => 0.0,
268            };
269
270            let child_origin = Pointf::new(
271                content_origin.x + node.margin.left + x_offset,
272                y + node.margin.top,
273            );
274            let child_size = Sizef::new(allocated_width, allocated_height);
275
276            self.arrange_node(child, tree, measured, child_origin, child_size, result);
277
278            y += allocated_height + node.margin.vertical();
279        }
280    }
281}
282
283impl LayoutResult {
284    pub fn get(&self, id: WidgetId) -> Option<&LayoutBox> {
285        self.boxes.get(&id)
286    }
287
288    pub fn iter(&self) -> impl Iterator<Item = (&WidgetId, &LayoutBox)> {
289        self.boxes.iter()
290    }
291}
292
293fn intersect_constraints(a: LayoutConstraints, b: LayoutConstraints) -> LayoutConstraints {
294    LayoutConstraints {
295        min_width: max_option(a.min_width, b.min_width),
296        max_width: min_option(a.max_width, b.max_width),
297        min_height: max_option(a.min_height, b.min_height),
298        max_height: min_option(a.max_height, b.max_height),
299    }
300}
301
302fn derive_child_constraints(
303    direction: LayoutDirection,
304    parent_size: Sizef,
305    padding: Insetsf,
306    margin: Insetsf,
307) -> LayoutConstraints {
308    let content_width = (parent_size.width - padding.horizontal()).max(0.0);
309    let content_height = (parent_size.height - padding.vertical()).max(0.0);
310
311    match direction {
312        LayoutDirection::Row => LayoutConstraints {
313            min_width: None,
314            max_width: Some((content_width - margin.horizontal()).max(0.0)),
315            min_height: None,
316            max_height: Some((content_height - margin.vertical()).max(0.0)),
317        },
318        LayoutDirection::Column => LayoutConstraints {
319            min_width: None,
320            max_width: Some((content_width - margin.horizontal()).max(0.0)),
321            min_height: None,
322            max_height: Some((content_height - margin.vertical()).max(0.0)),
323        },
324    }
325}
326
327fn clamp_size(size: Sizef, constraints: LayoutConstraints) -> Sizef {
328    Sizef::new(
329        clamp_value(size.width, constraints.min_width, constraints.max_width),
330        clamp_value(size.height, constraints.min_height, constraints.max_height),
331    )
332}
333
334fn clamp_value(value: f32, min: Option<f32>, max: Option<f32>) -> f32 {
335    let mut result = value;
336    if let Some(min) = min {
337        if result < min {
338            result = min;
339        }
340    }
341    if let Some(max) = max {
342        if result > max {
343            result = max;
344        }
345    }
346    result
347}
348
349fn max_option(a: Option<f32>, b: Option<f32>) -> Option<f32> {
350    match (a, b) {
351        (Some(a), Some(b)) => Some(a.max(b)),
352        (Some(a), None) => Some(a),
353        (None, Some(b)) => Some(b),
354        (None, None) => None,
355    }
356}
357
358fn min_option(a: Option<f32>, b: Option<f32>) -> Option<f32> {
359    match (a, b) {
360        (Some(a), Some(b)) => Some(a.min(b)),
361        (Some(a), None) => Some(a),
362        (None, Some(b)) => Some(b),
363        (None, None) => None,
364    }
365}
366
367#[cfg(test)]
368mod tests {
369    use alloc::boxed::Box;
370
371    use crate::{Tree, Widget, WidgetId};
372
373    use super::*;
374
375    struct FixedWidget {
376        id: WidgetId,
377        size: Sizef,
378    }
379
380    impl FixedWidget {
381        fn new(size: Sizef) -> Self {
382            Self {
383                id: WidgetId::new(),
384                size,
385            }
386        }
387    }
388
389    impl Widget for FixedWidget {
390        fn id(&self) -> WidgetId {
391            self.id
392        }
393
394        fn layout(&self, constraints: LayoutConstraints) -> Sizef {
395            clamp_size(self.size, constraints)
396        }
397    }
398
399    fn fixed_constraints(width: f32, height: f32) -> LayoutConstraints {
400        LayoutConstraints {
401            min_width: Some(width),
402            max_width: Some(width),
403            min_height: Some(height),
404            max_height: Some(height),
405        }
406    }
407
408    #[test]
409    fn single_widget_matches_constraints() {
410        let mut tree = Tree::new();
411        let widget = FixedWidget::new(Sizef::new(50.0, 30.0));
412        let id = widget.id();
413        tree.insert(Box::new(widget), None);
414
415        let result = LayoutEngine::new().compute(&tree, fixed_constraints(100.0, 80.0));
416        let box_ = result.get(id).unwrap();
417
418        assert_eq!(box_.origin, Pointf::zero());
419        assert_eq!(box_.size, Sizef::new(100.0, 80.0));
420    }
421
422    #[test]
423    fn row_lays_out_children_left_to_right() {
424        let mut tree = Tree::new();
425        let root_widget = FixedWidget::new(Sizef::new(300.0, 100.0));
426        let root = root_widget.id();
427        tree.insert(Box::new(root_widget), None);
428
429        let sizes = [
430            Sizef::new(50.0, 40.0),
431            Sizef::new(75.0, 60.0),
432            Sizef::new(100.0, 30.0),
433        ];
434        let mut child_ids = Vec::with_capacity(sizes.len());
435        for size in sizes {
436            let widget = FixedWidget::new(size);
437            child_ids.push(widget.id());
438            tree.insert(Box::new(widget), Some(root));
439        }
440
441        let mut engine = LayoutEngine::new();
442        engine.set_node(LayoutNode {
443            id: root,
444            direction: LayoutDirection::Row,
445            ..LayoutNode::default()
446        });
447
448        let result = engine.compute(&tree, fixed_constraints(300.0, 100.0));
449
450        assert_eq!(result.get(root).unwrap().size, Sizef::new(300.0, 100.0));
451
452        let mut x = 0.0;
453        for (expected, &id) in sizes.iter().zip(child_ids.iter()) {
454            let box_ = result.get(id).unwrap();
455            assert_eq!(box_.origin.x, x);
456            assert_eq!(box_.origin.y, 0.0);
457            assert_eq!(box_.size, *expected);
458            x += expected.width;
459        }
460    }
461
462    #[test]
463    fn row_flex_grow_distributes_remaining_space() {
464        let mut tree = Tree::new();
465        let root_widget = FixedWidget::new(Sizef::new(300.0, 100.0));
466        let root = root_widget.id();
467        tree.insert(Box::new(root_widget), None);
468
469        let a = FixedWidget::new(Sizef::new(50.0, 40.0));
470        let b = FixedWidget::new(Sizef::new(50.0, 40.0));
471        let c = FixedWidget::new(Sizef::new(50.0, 40.0));
472        let a_id = a.id();
473        let b_id = b.id();
474        let c_id = c.id();
475        tree.insert(Box::new(a), Some(root));
476        tree.insert(Box::new(b), Some(root));
477        tree.insert(Box::new(c), Some(root));
478
479        let mut engine = LayoutEngine::new();
480        engine
481            .set_node(LayoutNode {
482                id: root,
483                direction: LayoutDirection::Row,
484                ..LayoutNode::default()
485            })
486            .set_node(LayoutNode {
487                id: a_id,
488                flex_grow: 1.0,
489                ..LayoutNode::default()
490            })
491            .set_node(LayoutNode {
492                id: b_id,
493                flex_grow: 2.0,
494                ..LayoutNode::default()
495            });
496
497        let result = engine.compute(&tree, fixed_constraints(300.0, 100.0));
498
499        let a_box = result.get(a_id).unwrap();
500        let b_box = result.get(b_id).unwrap();
501        let c_box = result.get(c_id).unwrap();
502
503        assert_eq!(c_box.size.width, 50.0);
504        assert_eq!(a_box.size.width, 100.0);
505        assert_eq!(b_box.size.width, 150.0);
506        assert_eq!(a_box.origin.x, 0.0);
507        assert_eq!(b_box.origin.x, 100.0);
508        assert_eq!(c_box.origin.x, 250.0);
509    }
510
511    #[test]
512    fn column_respects_padding_and_margin() {
513        let mut tree = Tree::new();
514        let root_widget = FixedWidget::new(Sizef::new(200.0, 200.0));
515        let root = root_widget.id();
516        tree.insert(Box::new(root_widget), None);
517
518        let child = FixedWidget::new(Sizef::new(50.0, 50.0));
519        let child_id = child.id();
520        tree.insert(Box::new(child), Some(root));
521
522        let mut engine = LayoutEngine::new();
523        engine
524            .set_node(LayoutNode {
525                id: root,
526                direction: LayoutDirection::Column,
527                padding: Insetsf::uniform(10.0),
528                ..LayoutNode::default()
529            })
530            .set_node(LayoutNode {
531                id: child_id,
532                margin: Insetsf::uniform(5.0),
533                ..LayoutNode::default()
534            });
535
536        let result = engine.compute(&tree, fixed_constraints(200.0, 200.0));
537
538        let child_box = result.get(child_id).unwrap();
539        assert_eq!(child_box.origin, Pointf::new(15.0, 15.0));
540        assert_eq!(child_box.size, Sizef::new(50.0, 50.0));
541    }
542
543    #[test]
544    fn row_center_alignment_positions_children_middle() {
545        let mut tree = Tree::new();
546        let root_widget = FixedWidget::new(Sizef::new(300.0, 100.0));
547        let root = root_widget.id();
548        tree.insert(Box::new(root_widget), None);
549
550        let child = FixedWidget::new(Sizef::new(50.0, 40.0));
551        let child_id = child.id();
552        tree.insert(Box::new(child), Some(root));
553
554        let mut engine = LayoutEngine::new();
555        engine
556            .set_node(LayoutNode {
557                id: root,
558                direction: LayoutDirection::Row,
559                ..LayoutNode::default()
560            })
561            .set_node(LayoutNode {
562                id: child_id,
563                alignment: Alignment::Center,
564                ..LayoutNode::default()
565            });
566
567        let result = engine.compute(&tree, fixed_constraints(300.0, 100.0));
568
569        let child_box = result.get(child_id).unwrap();
570        assert_eq!(child_box.origin.x, 0.0);
571        assert_eq!(child_box.origin.y, 30.0);
572        assert_eq!(child_box.size, Sizef::new(50.0, 40.0));
573    }
574}