martensite 0.3.0

A retained-mode, GPU-accelerated graphical user interface framework for Rust.
Documentation
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
//! `Flex` widget: row/column flexbox layout for multiple children.
//!
//! The `Flex` widget arranges its children along a main axis (horizontal
//! for `Row`, vertical for `Column`) and aligns them on the cross axis.
//! It supports gaps between children and main-axis distribution.

use accesskit::Node as AccessKitNode;
use glam::Vec2;
use martensite_core::widget::{LayoutConstraints, LayoutContext, Widget};
use martensite_core::Rect;

/// The direction of flex layout.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub enum FlexDirection {
    /// Children are arranged horizontally (left to right).
    #[default]
    Row,
    /// Children are arranged vertically (top to bottom).
    Column,
}

impl FlexDirection {
    /// Returns `true` if this is a horizontal (row) direction.
    #[inline]
    pub fn is_row(self) -> bool {
        matches!(self, Self::Row)
    }

    /// Returns `true` if this is a vertical (column) direction.
    #[inline]
    pub fn is_column(self) -> bool {
        matches!(self, Self::Column)
    }

    /// Returns the main-axis component of a `Vec2`.
    #[inline]
    pub fn main(self, v: Vec2) -> f32 {
        if self.is_row() {
            v.x
        } else {
            v.y
        }
    }

    /// Returns the cross-axis component of a `Vec2`.
    #[inline]
    pub fn cross(self, v: Vec2) -> f32 {
        if self.is_row() {
            v.y
        } else {
            v.x
        }
    }

    /// Constructs a `Vec2` from main and cross components.
    #[inline]
    pub fn vec(self, main: f32, cross: f32) -> Vec2 {
        if self.is_row() {
            Vec2::new(main, cross)
        } else {
            Vec2::new(cross, main)
        }
    }
}

/// How to distribute children along the main axis.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub enum MainAxisAlignment {
    /// Children are packed toward the start of the main axis.
    #[default]
    Start,
    /// Children are packed toward the end of the main axis.
    End,
    /// Children are centered along the main axis.
    Center,
    /// Children are evenly distributed with equal space between them.
    SpaceBetween,
    /// Children are evenly distributed with equal space around them.
    SpaceEvenly,
}

/// How to align children on the cross axis.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub enum CrossAxisAlignment {
    /// Children are stretched to fill the cross axis.
    #[default]
    Stretch,
    /// Children are aligned to the start of the cross axis.
    Start,
    /// Children are aligned to the end of the cross axis.
    End,
    /// Children are centered on the cross axis.
    Center,
}

/// A flex container widget that arranges children in a row or column.
pub struct Flex {
    /// The direction of layout (row or column).
    pub direction: FlexDirection,
    /// How to distribute children along the main axis.
    pub main_axis_alignment: MainAxisAlignment,
    /// How to align children on the cross axis.
    pub cross_axis_alignment: CrossAxisAlignment,
    /// Gap between children in logical pixels.
    pub gap: f32,
    /// The child widgets.
    pub children: Vec<Box<dyn Widget>>,
    /// Cached child sizes from the last measure pass.
    child_sizes: Vec<Vec2>,
    /// Cached bounds from the last layout pass.
    cached_bounds: Rect,
}

impl Flex {
    /// Creates a new flex container with the given direction.
    pub fn new(direction: FlexDirection) -> Self {
        Self {
            direction,
            main_axis_alignment: MainAxisAlignment::default(),
            cross_axis_alignment: CrossAxisAlignment::default(),
            gap: 0.0,
            children: Vec::new(),
            child_sizes: Vec::new(),
            cached_bounds: Rect::default(),
        }
    }

    /// Creates a new row (horizontal flex).
    #[inline]
    pub fn row() -> Self {
        Self::new(FlexDirection::Row)
    }

    /// Creates a new column (vertical flex).
    #[inline]
    pub fn column() -> Self {
        Self::new(FlexDirection::Column)
    }

    /// Sets the main axis alignment.
    #[inline]
    pub fn main_axis_alignment(mut self, alignment: MainAxisAlignment) -> Self {
        self.main_axis_alignment = alignment;
        self
    }

    /// Sets the cross axis alignment.
    #[inline]
    pub fn cross_axis_alignment(mut self, alignment: CrossAxisAlignment) -> Self {
        self.cross_axis_alignment = alignment;
        self
    }

    /// Sets the gap between children.
    #[inline]
    pub fn gap(mut self, gap: f32) -> Self {
        self.gap = gap;
        self
    }

    /// Adds a child widget.
    #[inline]
    pub fn child(mut self, child: impl Widget + 'static) -> Self {
        self.children.push(Box::new(child));
        self
    }

    /// Adds multiple child widgets.
    #[inline]
    pub fn children(mut self, children: impl IntoIterator<Item = Box<dyn Widget>>) -> Self {
        self.children.extend(children);
        self
    }

    /// Returns the number of children.
    #[inline]
    pub fn child_count(&self) -> usize {
        self.children.len()
    }

    /// Computes the main-axis offset for each child given the total
    /// main-axis size and the total children main-axis size.
    fn compute_main_offsets(&self, total_main: f32, children_main: f32) -> Vec<f32> {
        let n = self.children.len();
        if n == 0 {
            return vec![];
        }

        // Note: children_main already includes total_gap (see caller),
        // so free_space = total_main - sum(child_sizes) - total_gap.
        // This is the space available for alignment distribution.
        let free_space = (total_main - children_main).max(0.0);

        match self.main_axis_alignment {
            MainAxisAlignment::Start => {
                let mut offsets = Vec::with_capacity(n);
                let mut cursor = 0.0f32;
                for i in 0..n {
                    offsets.push(cursor);
                    cursor += self
                        .direction
                        .main(self.child_sizes.get(i).copied().unwrap_or(Vec2::ZERO));
                    cursor += self.gap;
                }
                offsets
            }
            MainAxisAlignment::End => {
                let mut offsets = Vec::with_capacity(n);
                let mut cursor = free_space;
                for i in 0..n {
                    offsets.push(cursor);
                    cursor += self
                        .direction
                        .main(self.child_sizes.get(i).copied().unwrap_or(Vec2::ZERO));
                    cursor += self.gap;
                }
                offsets
            }
            MainAxisAlignment::Center => {
                let mut offsets = Vec::with_capacity(n);
                let mut cursor = free_space / 2.0;
                for i in 0..n {
                    offsets.push(cursor);
                    cursor += self
                        .direction
                        .main(self.child_sizes.get(i).copied().unwrap_or(Vec2::ZERO));
                    cursor += self.gap;
                }
                offsets
            }
            MainAxisAlignment::SpaceBetween => {
                let mut offsets = Vec::with_capacity(n);
                let space_between = if n > 1 {
                    free_space / (n - 1) as f32
                } else {
                    0.0
                };
                let mut cursor = 0.0f32;
                for i in 0..n {
                    offsets.push(cursor);
                    cursor += self
                        .direction
                        .main(self.child_sizes.get(i).copied().unwrap_or(Vec2::ZERO));
                    cursor += self.gap + space_between;
                }
                offsets
            }
            MainAxisAlignment::SpaceEvenly => {
                let mut offsets = Vec::with_capacity(n);
                // free_space = total_main - sum(child_sizes) - total_gap
                // We distribute free_space evenly across (n+1) slots.
                // Inter-child spacing is gap + space; leading/trailing is space.
                let space = if n > 0 {
                    free_space / (n + 1) as f32
                } else {
                    0.0
                };
                let mut cursor = space;
                for i in 0..n {
                    offsets.push(cursor);
                    cursor += self
                        .direction
                        .main(self.child_sizes.get(i).copied().unwrap_or(Vec2::ZERO));
                    cursor += self.gap + space;
                }
                offsets
            }
        }
    }
}

impl Widget for Flex {
    fn measure(&mut self, cx: &mut LayoutContext, constraints: LayoutConstraints) -> Vec2 {
        let n = self.children.len();
        if n == 0 {
            return Vec2::ZERO;
        }

        self.child_sizes.clear();
        self.child_sizes.reserve(n);

        let mut total_main = 0.0f32;
        let mut max_cross = 0.0f32;
        let total_gap = self.gap * (n.saturating_sub(1)) as f32;

        for child in &mut self.children {
            // Give each child the remaining main-axis space after
            // accounting for previously-measured siblings and gaps.
            // Only check the main-axis constraint, not the cross-axis.
            let max_main = self.direction.main(constraints.max_size);
            let remaining_main = if max_main.is_finite() {
                (max_main - total_main - total_gap).max(0.0)
            } else {
                f32::MAX
            };
            let cross_limit = self.direction.cross(constraints.max_size);
            let child_max = if self.direction.is_row() {
                Vec2::new(remaining_main, cross_limit)
            } else {
                Vec2::new(cross_limit, remaining_main)
            };
            let child_constraints = LayoutConstraints {
                min_size: Vec2::ZERO,
                max_size: child_max,
            };
            let size = child.measure(cx, child_constraints);
            self.child_sizes.push(size);
            total_main += self.direction.main(size);
            max_cross = max_cross.max(self.direction.cross(size));
        }

        total_main += total_gap;

        self.direction.vec(total_main, max_cross)
    }

    fn layout(&mut self, cx: &mut LayoutContext, bounds: Rect) {
        self.cached_bounds = bounds;
        let n = self.children.len();
        if n == 0 {
            return;
        }

        let total_main = self.direction.main(bounds.size);
        let cross_size = self.direction.cross(bounds.size);

        let children_main: f32 = self
            .child_sizes
            .iter()
            .map(|s| self.direction.main(*s))
            .sum::<f32>()
            + self.gap * (n.saturating_sub(1)) as f32;

        let main_offsets = self.compute_main_offsets(total_main, children_main);
        let cross_alignment = self.cross_axis_alignment;
        let direction = self.direction;

        for (i, child) in self.children.iter_mut().enumerate() {
            let child_size = self.child_sizes.get(i).copied().unwrap_or(Vec2::ZERO);
            let child_main = direction.main(child_size);
            let child_cross = if matches!(cross_alignment, CrossAxisAlignment::Stretch) {
                cross_size
            } else {
                direction.cross(child_size)
            };

            let main_offset = main_offsets[i];
            let cross_offset = match cross_alignment {
                CrossAxisAlignment::Stretch | CrossAxisAlignment::Start => 0.0,
                CrossAxisAlignment::End => (cross_size - child_cross).max(0.0),
                CrossAxisAlignment::Center => ((cross_size - child_cross) / 2.0).max(0.0),
            };

            let (x, y) = if direction.is_row() {
                (
                    bounds.origin.x + main_offset,
                    bounds.origin.y + cross_offset,
                )
            } else {
                (
                    bounds.origin.x + cross_offset,
                    bounds.origin.y + main_offset,
                )
            };

            // For Row: width=child_main, height=child_cross
            // For Column: width=child_cross, height=child_main
            let (w, h) = if direction.is_row() {
                (child_main, child_cross)
            } else {
                (child_cross, child_main)
            };
            let child_bounds = Rect::new(x, y, w, h);
            child.layout(cx, child_bounds);
        }
    }

    fn accessibility(&self, node: &mut AccessKitNode) {
        node.set_role(accesskit::Role::GenericContainer);
    }
}

impl std::fmt::Debug for Flex {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Flex")
            .field("direction", &self.direction)
            .field("main_axis_alignment", &self.main_axis_alignment)
            .field("cross_axis_alignment", &self.cross_axis_alignment)
            .field("gap", &self.gap)
            .field("child_count", &self.children.len())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use martensite_core::widget::DummyWidget;
    use martensite_core::HotNode;

    fn make_cx(hot: &mut HotNode) -> LayoutContext<'_> {
        LayoutContext { hot }
    }

    #[test]
    fn flex_row_new() {
        let f = Flex::row();
        assert_eq!(f.direction, FlexDirection::Row);
        assert!(f.children.is_empty());
    }

    #[test]
    fn flex_column_new() {
        let f = Flex::column();
        assert_eq!(f.direction, FlexDirection::Column);
    }

    #[test]
    fn flex_direction_helpers() {
        assert!(FlexDirection::Row.is_row());
        assert!(!FlexDirection::Row.is_column());
        assert!(FlexDirection::Column.is_column());
        let v = Vec2::new(10.0, 20.0);
        assert_eq!(FlexDirection::Row.main(v), 10.0);
        assert_eq!(FlexDirection::Row.cross(v), 20.0);
        assert_eq!(FlexDirection::Column.main(v), 20.0);
        assert_eq!(FlexDirection::Column.cross(v), 10.0);
    }

    #[test]
    fn flex_measure_empty() {
        let mut hot = HotNode::new(taffy::NodeId::new(1));
        let mut cx = make_cx(&mut hot);
        let mut f = Flex::row();
        let size = f.measure(
            &mut cx,
            LayoutConstraints {
                min_size: Vec2::ZERO,
                max_size: Vec2::new(100.0, 100.0),
            },
        );
        assert_eq!(size, Vec2::ZERO);
    }

    #[test]
    fn flex_measure_with_dummy_children() {
        let mut hot = HotNode::new(taffy::NodeId::new(1));
        let mut cx = make_cx(&mut hot);
        let mut f = Flex::row()
            .child(DummyWidget)
            .child(DummyWidget)
            .child(DummyWidget);
        let size = f.measure(
            &mut cx,
            LayoutConstraints {
                min_size: Vec2::ZERO,
                max_size: Vec2::new(100.0, 100.0),
            },
        );
        // DummyWidgets measure ZERO, so flex is ZERO
        assert_eq!(size, Vec2::ZERO);
    }

    #[test]
    fn flex_layout_positions_children() {
        let mut hot = HotNode::new(taffy::NodeId::new(1));
        let mut cx = make_cx(&mut hot);
        let mut f = Flex::row().child(DummyWidget).child(DummyWidget);
        // Measure first to populate child_sizes
        f.measure(
            &mut cx,
            LayoutConstraints {
                min_size: Vec2::ZERO,
                max_size: Vec2::new(100.0, 100.0),
            },
        );
        // Layout
        f.layout(&mut cx, Rect::new(0.0, 0.0, 200.0, 100.0));
        assert_eq!(f.cached_bounds, Rect::new(0.0, 0.0, 200.0, 100.0));
    }

    #[test]
    fn flex_main_axis_alignment_center() {
        let mut hot = HotNode::new(taffy::NodeId::new(1));
        let mut cx = make_cx(&mut hot);
        let mut f = Flex::row()
            .main_axis_alignment(MainAxisAlignment::Center)
            .child(DummyWidget);
        f.measure(
            &mut cx,
            LayoutConstraints {
                min_size: Vec2::ZERO,
                max_size: Vec2::new(100.0, 100.0),
            },
        );
        f.layout(&mut cx, Rect::new(0.0, 0.0, 100.0, 50.0));
        // Should not panic
    }

    #[test]
    fn flex_space_between() {
        let mut hot = HotNode::new(taffy::NodeId::new(1));
        let mut cx = make_cx(&mut hot);
        let mut f = Flex::row()
            .main_axis_alignment(MainAxisAlignment::SpaceBetween)
            .child(DummyWidget)
            .child(DummyWidget);
        f.measure(
            &mut cx,
            LayoutConstraints {
                min_size: Vec2::ZERO,
                max_size: Vec2::new(100.0, 100.0),
            },
        );
        f.layout(&mut cx, Rect::new(0.0, 0.0, 100.0, 50.0));
    }

    #[test]
    fn flex_space_evenly() {
        let mut hot = HotNode::new(taffy::NodeId::new(1));
        let mut cx = make_cx(&mut hot);
        let mut f = Flex::row()
            .main_axis_alignment(MainAxisAlignment::SpaceEvenly)
            .child(DummyWidget);
        f.measure(
            &mut cx,
            LayoutConstraints {
                min_size: Vec2::ZERO,
                max_size: Vec2::new(100.0, 100.0),
            },
        );
        f.layout(&mut cx, Rect::new(0.0, 0.0, 100.0, 50.0));
    }

    #[test]
    fn flex_cross_axis_alignment() {
        let mut hot = HotNode::new(taffy::NodeId::new(1));
        let mut cx = make_cx(&mut hot);
        let mut f = Flex::row()
            .cross_axis_alignment(CrossAxisAlignment::Center)
            .child(DummyWidget);
        f.measure(
            &mut cx,
            LayoutConstraints {
                min_size: Vec2::ZERO,
                max_size: Vec2::new(100.0, 100.0),
            },
        );
        f.layout(&mut cx, Rect::new(0.0, 0.0, 100.0, 50.0));
    }

    #[test]
    fn flex_gap() {
        let mut hot = HotNode::new(taffy::NodeId::new(1));
        let mut cx = make_cx(&mut hot);
        let mut f = Flex::row().gap(10.0).child(DummyWidget).child(DummyWidget);
        let size = f.measure(
            &mut cx,
            LayoutConstraints {
                min_size: Vec2::ZERO,
                max_size: Vec2::new(100.0, 100.0),
            },
        );
        // DummyWidgets are zero, so size is just gap
        assert_eq!(size.x, 10.0);
    }

    #[test]
    fn flex_debug_format() {
        let f = Flex::row().gap(5.0).child(DummyWidget);
        let debug = format!("{:?}", f);
        assert!(debug.contains("Flex"));
        assert!(debug.contains("Row"));
    }
}