guido 0.11.0

A reactive Rust GUI library using wgpu for Wayland layer shell widgets
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
//! Flexbox-style layout algorithm for rows and columns.
//!
//! This module implements a flexbox-inspired layout system that arranges
//! children along a main axis with configurable alignment and spacing.
//!
//! ## Main Axis vs Cross Axis
//!
//! - **Row**: Main axis is horizontal, cross axis is vertical
//! - **Column**: Main axis is vertical, cross axis is horizontal
//!
//! ## Alignment Options
//!
//! **Main axis** ([`MainAlignment`]):
//! - `Start`, `Center`, `End` - Position children at start/center/end
//! - `SpaceBetween` - Equal space between children, none at edges
//! - `SpaceAround` - Equal space around children (half at edges)
//! - `SpaceEvenly` - Equal space including edges
//!
//! **Cross axis** ([`CrossAlignment`]):
//! - `Start`, `Center`, `End` - Align children along cross axis
//! - `Stretch` - Stretch children to fill cross axis (default)
//!
//! [`Flex::center`] sets both to `Center`.
//!
//! ## Usage
//!
//! ```no_run
//! # use guido::prelude::*;
//! # let (button_a, button_b, button_c) = (text("a"), text("b"), text("c"));
//! container()
//!     .layout(Flex::row().spacing(8.0).main_alignment(MainAlignment::Center))
//!     .children([button_a, button_b, button_c]);
//! ```

use super::{Axis, Constraints, CrossAlignment, Layout, MainAlignment, Size};
use crate::{
    reactive::{IntoSignal, Prop, Signal},
    tree::{LayoutCtx, Tree, WidgetId},
};

/// Children with main-axis size below this threshold are treated as invisible
/// for spacing purposes (no gap is added on either side).
const MIN_VISIBLE_SIZE: f32 = 0.5;

/// Flex layout for rows and columns
pub struct Flex {
    direction: Signal<Axis>,
    spacing: Prop<f32>,
    main_alignment: Prop<MainAlignment>,
    cross_alignment: Prop<CrossAlignment>,

    child_sizes: Vec<Size>,
    fill_indices: Vec<usize>,
}

impl Flex {
    /// Create a new flex layout with the given direction
    ///
    /// Default alignments match CSS Flexbox:
    /// - `main_alignment`: `Start` (CSS `justify-content: flex-start`)
    /// - `cross_alignment`: `Stretch` (CSS `align-items: stretch`)
    pub fn new<M>(direction: impl IntoSignal<Axis, M>) -> Self {
        Self {
            direction: direction.into_signal(),
            spacing: Prop::Unset,
            main_alignment: Prop::Unset,
            cross_alignment: Prop::Unset,
            child_sizes: Vec::with_capacity(8),
            fill_indices: Vec::new(),
        }
    }

    /// Create a row layout
    pub fn row() -> Self {
        Self::new(Axis::Horizontal)
    }

    /// Create a column layout
    pub fn column() -> Self {
        Self::new(Axis::Vertical)
    }

    /// Set the spacing between children
    pub fn spacing<M>(mut self, spacing: impl IntoSignal<f32, M>) -> Self {
        self.spacing = spacing.into_prop();
        self
    }

    /// Set the main axis alignment
    pub fn main_alignment<M>(mut self, alignment: impl IntoSignal<MainAlignment, M>) -> Self {
        self.main_alignment = alignment.into_prop();
        self
    }

    /// Set the cross axis alignment
    pub fn cross_alignment<M>(mut self, alignment: impl IntoSignal<CrossAlignment, M>) -> Self {
        self.cross_alignment = alignment.into_prop();
        self
    }

    /// Centre the children on both axes: shorthand for
    /// [`main_alignment(MainAlignment::Center)`](Self::main_alignment) and
    /// [`cross_alignment(CrossAlignment::Center)`](Self::cross_alignment).
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// container()
    ///     .layout(Flex::column().spacing(4.0).center())
    ///     .children([text("Locked"), text("Type your password")]);
    /// ```
    pub fn center(self) -> Self {
        self.main_alignment(MainAlignment::Center)
            .cross_alignment(CrossAlignment::Center)
    }

    /// Calculate initial offset and spacing between children based on main axis alignment
    fn calc_main_axis_spacing(
        &self,
        main_align: MainAlignment,
        spacing: f32,
        free_space: f32,
        child_count: usize,
    ) -> (f32, f32) {
        match main_align {
            MainAlignment::Start => (0.0, spacing),
            MainAlignment::Center => (free_space / 2.0, spacing),
            MainAlignment::End => (free_space, spacing),
            MainAlignment::SpaceBetween => {
                if child_count > 1 {
                    (0.0, free_space / (child_count - 1) as f32 + spacing)
                } else {
                    (0.0, spacing)
                }
            }
            MainAlignment::SpaceAround => {
                let space = free_space / child_count as f32;
                (space / 2.0, space + spacing)
            }
            MainAlignment::SpaceEvenly => {
                let space = free_space / (child_count + 1) as f32;
                (space, space + spacing)
            }
        }
    }

    /// Layout children along the given axis
    fn layout_axis(
        &mut self,
        ctx: &mut LayoutCtx,
        children: &[WidgetId],
        constraints: Constraints,
        origin: (f32, f32),
        axis: Axis,
    ) -> Size {
        let spacing = self.spacing.get_or(0.0);
        let main_align = self.main_alignment.get_or(MainAlignment::Start);
        let cross_align = self.cross_alignment.get_or(CrossAlignment::Stretch);

        // Get main/cross axis constraints based on direction
        let (main_max, cross_min, cross_max) = match axis {
            Axis::Horizontal => (
                constraints.max_width,
                constraints.min_height,
                constraints.max_height,
            ),
            Axis::Vertical => (
                constraints.max_height,
                constraints.min_width,
                constraints.max_width,
            ),
        };

        // For Stretch alignment, use min constraint if set
        let stretch_cross = if cross_align == CrossAlignment::Stretch && cross_min > 0.0 {
            Some(cross_min)
        } else {
            None
        };

        let child_constraints = match axis {
            Axis::Horizontal => Constraints {
                min_width: 0.0,
                min_height: stretch_cross.unwrap_or(0.0),
                max_width: main_max,
                max_height: stretch_cross.unwrap_or(cross_max),
            },
            Axis::Vertical => Constraints {
                min_width: stretch_cross.unwrap_or(0.0),
                min_height: 0.0,
                max_width: stretch_cross.unwrap_or(cross_max),
                max_height: main_max,
            },
        };

        // Pre-allocate child_sizes
        self.child_sizes.clear();
        self.child_sizes.resize(children.len(), Size::zero());

        // Pass 1: layout non-fill children and collect fill child indices
        let mut non_fill_main = 0.0f32;
        let mut max_cross = 0.0f32;
        self.fill_indices.clear();

        for (i, &child_id) in children.iter().enumerate() {
            let is_fill = ctx
                .tree_ref()
                .with_widget(child_id, |w| match axis {
                    Axis::Horizontal => w.layout_hints().fill_width,
                    Axis::Vertical => w.layout_hints().fill_height,
                })
                .unwrap_or(false);

            if is_fill {
                self.fill_indices.push(i);
            } else if let Some(size) = ctx.layout_child(child_id, child_constraints) {
                non_fill_main += size.main_axis(axis);
                max_cross = max_cross.max(size.cross_axis(axis));
                self.child_sizes[i] = size;
            }
        }

        // Compute fill distribution
        let total_spacing = if children.len() > 1 {
            spacing * (children.len() - 1) as f32
        } else {
            0.0
        };
        let per_fill = if !self.fill_indices.is_empty() {
            let remaining = (main_max - non_fill_main - total_spacing).max(0.0);
            remaining / self.fill_indices.len() as f32
        } else {
            0.0
        };

        // Pass 2: layout fill children with tight main-axis constraints
        if !self.fill_indices.is_empty() {
            let fill_constraints = match axis {
                Axis::Horizontal => Constraints {
                    min_width: per_fill,
                    max_width: per_fill,
                    ..child_constraints
                },
                Axis::Vertical => Constraints {
                    min_height: per_fill,
                    max_height: per_fill,
                    ..child_constraints
                },
            };

            for &i in &self.fill_indices {
                let child_id = children[i];
                if let Some(size) = ctx.layout_child(child_id, fill_constraints) {
                    max_cross = max_cross.max(size.cross_axis(axis));
                    self.child_sizes[i] = size;
                }
            }
        }

        // Compute total main-axis usage
        let mut children_main: f32 = self.child_sizes.iter().map(|s| s.main_axis(axis)).sum();

        // Calculate final dimensions
        let (main_min, cross_constraint_min) = match axis {
            Axis::Horizontal => (constraints.min_width, constraints.min_height),
            Axis::Vertical => (constraints.min_height, constraints.min_width),
        };

        let cross_size = max_cross.max(cross_constraint_min).min(cross_max);

        // For Stretch: if we didn't have a known cross size before, re-layout children
        // with the computed cross size. Fill children get tight main-axis constraints.
        //
        // Skip children that already match cross_size — re-constraining them to their
        // own size is a no-op for sizing but creates tight constraints that turn them
        // into relayout boundaries, preventing dynamic content changes from propagating
        // up to recompute cross_size.
        if cross_align == CrossAlignment::Stretch && stretch_cross.is_none() && cross_size > 0.0 {
            children_main = 0.0;
            let mut fill_cursor = 0;
            for (i, &child_id) in children.iter().enumerate() {
                if (self.child_sizes[i].cross_axis(axis) - cross_size).abs() < 0.5 {
                    children_main += self.child_sizes[i].main_axis(axis);
                    if fill_cursor < self.fill_indices.len() && self.fill_indices[fill_cursor] == i
                    {
                        fill_cursor += 1;
                    }
                    continue;
                }
                let child_is_fill =
                    fill_cursor < self.fill_indices.len() && self.fill_indices[fill_cursor] == i;
                if child_is_fill {
                    fill_cursor += 1;
                }
                let main_constraint = if child_is_fill { per_fill } else { main_max };
                let stretch_constraints = match axis {
                    Axis::Horizontal => Constraints {
                        min_width: if child_is_fill { per_fill } else { 0.0 },
                        min_height: cross_size,
                        max_width: main_constraint,
                        max_height: cross_size,
                    },
                    Axis::Vertical => Constraints {
                        min_width: cross_size,
                        min_height: if child_is_fill { per_fill } else { 0.0 },
                        max_width: cross_size,
                        max_height: main_constraint,
                    },
                };
                if let Some(size) = ctx.layout_child(child_id, stretch_constraints) {
                    children_main += size.main_axis(axis);
                    self.child_sizes[i] = size;
                }
            }
        }

        // Collapse spacing around zero-sized children: a child with zero
        // main-axis size should not contribute a gap on either side.
        let visible_count = self
            .child_sizes
            .iter()
            .filter(|s| s.main_axis(axis) > MIN_VISIBLE_SIZE)
            .count();
        let visible_spacing = if visible_count > 1 {
            spacing * (visible_count - 1) as f32
        } else {
            0.0
        };
        let visible_total_main = children_main + visible_spacing;
        let main_size = match main_align {
            MainAlignment::SpaceBetween
            | MainAlignment::SpaceAround
            | MainAlignment::SpaceEvenly => main_max,
            MainAlignment::Start | MainAlignment::Center | MainAlignment::End => {
                visible_total_main.max(main_min).min(main_max)
            }
        };

        let (width, height) = match axis {
            Axis::Horizontal => (main_size, cross_size),
            Axis::Vertical => (cross_size, main_size),
        };
        let size = Size::new(width, height);

        // Position children
        let free_space = (main_size - children_main - visible_spacing).max(0.0);

        let (initial_offset, between_spacing) =
            self.calc_main_axis_spacing(main_align, spacing, free_space, visible_count);

        let mut main_pos = match axis {
            Axis::Horizontal => origin.0,
            Axis::Vertical => origin.1,
        } + initial_offset;

        // Baseline alignment needs the deepest baseline in the row before it
        // can place anything: every child shifts down by the difference
        // between it and its own.
        let max_baseline = if cross_align == CrossAlignment::Baseline && axis == Axis::Horizontal {
            children
                .iter()
                .enumerate()
                .map(|(i, &id)| {
                    baseline_of(ctx.tree_ref(), id, self.child_sizes[i].cross_axis(axis))
                })
                .fold(0.0f32, f32::max)
        } else {
            0.0
        };

        let mut prev_nonzero = false;
        for (i, &child_id) in children.iter().enumerate() {
            let child_size = self.child_sizes[i];
            let child_main = child_size.main_axis(axis);
            let child_cross = child_size.cross_axis(axis);

            // Add spacing only between consecutive non-zero-sized children
            if prev_nonzero && child_main > MIN_VISIBLE_SIZE {
                main_pos += between_spacing;
            }

            let cross_pos = match cross_align {
                CrossAlignment::Start => match axis {
                    Axis::Horizontal => origin.1,
                    Axis::Vertical => origin.0,
                },
                CrossAlignment::Center => match axis {
                    Axis::Horizontal => origin.1 + (cross_size - child_cross) / 2.0,
                    Axis::Vertical => origin.0 + (cross_size - child_cross) / 2.0,
                },
                CrossAlignment::End => match axis {
                    Axis::Horizontal => origin.1 + cross_size - child_cross,
                    Axis::Vertical => origin.0 + cross_size - child_cross,
                },
                CrossAlignment::Stretch => match axis {
                    Axis::Horizontal => origin.1,
                    Axis::Vertical => origin.0,
                },
                CrossAlignment::Baseline => match axis {
                    Axis::Horizontal => {
                        origin.1 + max_baseline - baseline_of(ctx.tree_ref(), child_id, child_cross)
                    }
                    // A column has no shared line to sit on.
                    Axis::Vertical => origin.0,
                },
            };

            let (x, y) = match axis {
                Axis::Horizontal => (main_pos, cross_pos),
                Axis::Vertical => (cross_pos, main_pos),
            };

            ctx.tree().set_origin(child_id, x, y);
            main_pos += child_main;

            if child_main > MIN_VISIBLE_SIZE {
                prev_nonzero = true;
            }
        }

        size
    }
}

impl Layout for Flex {
    fn layout(
        &mut self,
        ctx: &mut LayoutCtx,
        children: &[WidgetId],
        constraints: Constraints,
        origin: (f32, f32),
    ) -> Size {
        let direction = self.direction.get();
        self.layout_axis(ctx, children, constraints, origin, direction)
    }
}

/// Where a child sits on its baseline, for the purpose of lining a row up.
///
/// Leaves that draw text report one during layout. Anything else — a box, an
/// image — is treated as sitting on its own bottom edge, which is how CSS
/// aligns a baseline-less box among text.
fn baseline_of(tree: &Tree, id: WidgetId, cross_size: f32) -> f32 {
    tree.baseline(id).unwrap_or(cross_size)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::jobs;
    use crate::reactive::create_signal;
    use crate::widgets::container;

    fn frame(tree: &mut Tree, root: WidgetId) {
        jobs::pump_and_layout(tree, root, Constraints::new(0.0, 0.0, 400.0, 400.0));
    }

    /// A row becomes a column on a write, with the same widgets in the tree.
    ///
    /// The direction has always been held as `Signal<Axis>` and read through it
    /// on every pass — only `Flex::new`'s signature stood between here and a
    /// layout that answers to one. Asserted on the children's origins rather
    /// than on the container's size, because two boxes of the same size in a
    /// square make the row and the column the same size and only the placement
    /// tells them apart.
    #[test]
    fn a_row_becomes_a_column_when_its_direction_says_so() {
        let horizontal = create_signal(true);
        let axis = move || {
            if horizontal.get() {
                Axis::Horizontal
            } else {
                Axis::Vertical
            }
        };

        let mut tree = Tree::new();
        let root = tree.register(Box::new(container().layout(Flex::new(axis)).children(
            vec![
                container().width(20.0).height(20.0),
                container().width(20.0).height(20.0),
            ],
        )));
        tree.with_widget_mut(root, |w, id, t| w.register_children(t, id));

        frame(&mut tree, root);
        let kids = tree.get_children(root).to_vec();
        assert_eq!(kids.len(), 2, "two children, laid out");
        let second = tree.get_origin(kids[1]).expect("laid out");
        assert!(
            second.0 > 0.0 && second.1 == 0.0,
            "a row puts the second child to the right, got {second:?}"
        );

        horizontal.set(false);
        frame(&mut tree, root);

        let same_kids = tree.get_children(root).to_vec();
        assert_eq!(same_kids, kids, "the children were rebuilt, not relaid out");
        let second = tree.get_origin(kids[1]).expect("laid out");
        assert!(
            second.1 > 0.0 && second.0 == 0.0,
            "a column puts the second child below, got {second:?}"
        );
    }
}