guillotine 0.4.0

A no_std graphical user interface framework in Rust for embedded devices prioritizing resource efficiency and ergonomics.
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
//! Styling utilities.
use embedded_graphics::{
    pixelcolor::Rgb565,
    prelude::{PixelColor, Size},
};

use crate::{Constraints, DivStyle};

/// Physical top, right, bottom, and left insets in pixels.
///
/// Guillotine uses the same one-to-four-value shorthand ordering as CSS:
///
/// - `10`: all sides
/// - `(4, 8)`: vertical, horizontal
/// - `(4, 8, 12)`: top, horizontal, bottom
/// - `(4, 8, 12, 16)`: top, right, bottom, left
///
/// Insets are non-negative pixel lengths. Percentages, `auto`, logical edges, negative margins,
/// and margin collapsing are not supported.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Insets {
    /// Top inset.
    pub top: u32,
    /// Right inset.
    pub right: u32,
    /// Bottom inset.
    pub bottom: u32,
    /// Left inset.
    pub left: u32,
}

impl Insets {
    /// Insets with every edge set to zero.
    pub const ZERO: Self = Self::uniform(0);

    /// Creates insets in CSS order: top, right, bottom, left.
    pub const fn new(top: u32, right: u32, bottom: u32, left: u32) -> Self {
        Self { top, right, bottom, left }
    }

    /// Creates uniform insets from the given `value`.
    pub const fn uniform(value: u32) -> Self {
        Self::new(value, value, value, value)
    }

    /// Creates zero insets.
    pub const fn zero() -> Self {
        Self::ZERO
    }

    /// Returns the horizontal insets (`left + right`).
    pub const fn horizontal(self) -> u32 {
        self.left.saturating_add(self.right)
    }

    /// Returns the vertical insets (`top + bottom`).
    pub const fn vertical(self) -> u32 {
        self.top.saturating_add(self.bottom)
    }

    /// Returns the total horizontal and vertical inset as a size.
    pub const fn total_size(self) -> Size {
        Size::new(self.horizontal(), self.vertical())
    }

    /// Adds two sets of insets edge by edge using saturating arithmetic.
    pub const fn saturating_add(self, other: Self) -> Self {
        Self::new(
            self.top.saturating_add(other.top),
            self.right.saturating_add(other.right),
            self.bottom.saturating_add(other.bottom),
            self.left.saturating_add(other.left),
        )
    }
}

macro_rules! impl_insets_from {
    ($type:ty, $convert:expr) => {
        impl From<$type> for Insets {
            fn from(value: $type) -> Self {
                let convert = $convert;
                Self::uniform(convert(value))
            }
        }

        impl From<($type, $type)> for Insets {
            fn from((vertical, horizontal): ($type, $type)) -> Self {
                let convert = $convert;
                Self::new(
                    convert(vertical),
                    convert(horizontal),
                    convert(vertical),
                    convert(horizontal),
                )
            }
        }

        impl From<($type, $type, $type)> for Insets {
            fn from((top, horizontal, bottom): ($type, $type, $type)) -> Self {
                let convert = $convert;
                Self::new(convert(top), convert(horizontal), convert(bottom), convert(horizontal))
            }
        }

        impl From<($type, $type, $type, $type)> for Insets {
            fn from((top, right, bottom, left): ($type, $type, $type, $type)) -> Self {
                let convert = $convert;
                Self::new(convert(top), convert(right), convert(bottom), convert(left))
            }
        }
    };
}

impl_insets_from!(u32, |value: u32| value);
impl_insets_from!(usize, |value: usize| u32::try_from(value).unwrap_or(u32::MAX));
impl_insets_from!(i32, |value: i32| {
    assert!(value >= 0, "insets cannot be negative");
    value as u32
});

/// The style of a box, including margin, border, padding, and size.
pub(crate) struct BoxStyle {
    pub margin: Insets,
    pub border: Insets,
    pub padding: Insets,
    pub width: Option<u32>,
    pub height: Option<u32>,
}

impl BoxStyle {
    /// Returns the constraints for the border box by subtracting the margin from
    /// the given constraints.
    pub(crate) const fn border_constraints(&self, constraints: Constraints) -> Constraints {
        constraints.deflate(self.margin.total_size())
    }

    /// Returns loose constraints for the contents of a box, which lives inside the border
    /// and padding.
    pub(crate) fn content_constraints(&self, constraints: Constraints) -> Constraints {
        let border_constraints = self.border_constraints(constraints);
        let content_size = self.content_insets().total_size();

        // Configured dimensions describe the border box. Like CSS `border-box`, each configured
        // axis grows to contain its padding and border unless hard parent constraints prevent it.
        // An automatic axis keeps the constraints supplied by the parent.
        let border_constraints = border_constraints.with_exact_dimensions(
            self.width.map(|width| width.max(content_size.width)),
            self.height.map(|height| height.max(content_size.height)),
        );

        border_constraints.deflate(content_size).loosen()
    }

    /// Returns the content insets, i.e. `border + padding` on each edge.
    pub(crate) const fn content_insets(&self) -> Insets {
        self.border.saturating_add(self.padding)
    }
}

#[cfg(feature = "flexbox")]
#[derive(Clone, Copy)]
pub(crate) struct FlexItemStyle {
    pub flex_grow: u16,
    pub flex_basis: FlexBasis,
}

/// The initial main-axis size of a flex item before free space is distributed.
#[cfg(feature = "flexbox")]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum FlexBasis {
    /// The flex basis is determined by the content size.
    #[default]
    Auto,
    /// The flex basis is 0.
    Zero,
}

#[cfg(feature = "flexbox")]
impl FlexBasis {
    pub(crate) const fn resolve(self, auto: u32) -> u32 {
        match self {
            Self::Auto => auto,
            Self::Zero => 0,
        }
    }

    pub(crate) const fn is_zero(self) -> bool {
        matches!(self, Self::Zero)
    }
}

/// Common style shared by all element builders.
///
/// # Box model
///
/// ```text
/// ┌─────────────────────────┐
/// │         margin          │
/// │  ┌───────────────────┐  │
/// │  │      border       │  │
/// │  │  ┌─────────────┐  │  │
/// │  │  │   padding   │  │  │
/// │  │  │  ┌───────┐  │  │  │
/// │  │  │  │content│  │  │  │
/// │  │  │  └───────┘  │  │  │
/// │  │  └─────────────┘  │  │
/// │  └───────────────────┘  │
/// └─────────────────────────┘
/// ```
///
/// [`Self::margin`], [`Self::padding`], and [`Self::border`] use physical top/right/bottom/left
/// edges and accept CSS-like one-to-four-value shorthands through [`StyledElement`]. Adjacent
/// margins in rows and columns add together; they do not collapse.
///
/// [`StyledElement::size`], [`StyledElement::width`], and [`StyledElement::height`] configure the
/// border box. Padding and border are placed inside configured dimensions, while margin is added
/// outside them. A configured dimension grows to contain its padding and border when parent
/// constraints allow. An unconfigured dimension is sized automatically from the element's
/// contents. Guillotine supports non-negative pixel insets only, with one border color and no
/// border styles.
#[derive(PartialEq, Eq)]
pub struct Style<S: Default, C = Rgb565> {
    /// Margin insets: transparent space outside the border box.
    pub margin: Insets,
    /// Padding insets: space between the border and content.
    pub padding: Insets,
    /// Border widths.
    pub border: Insets,
    /// Border color shared by all four edges.
    pub border_color: Option<C>,
    /// Background color painted across the complete border box, beneath the border.
    pub background: Option<C>,
    /// Width of the border box.
    pub width: Option<u32>,
    /// Height of the border box.
    pub height: Option<u32>,
    #[cfg(feature = "flexbox")]
    /// Flex grow factor.
    pub flex_grow: u16,
    /// Flex basis.
    #[cfg(feature = "flexbox")]
    pub flex_basis: FlexBasis,
    /// Specific style properties for each element kind.
    pub specific: S,
}

impl<S: Default, C> Default for Style<S, C> {
    fn default() -> Self {
        Self {
            margin: Insets::ZERO,
            padding: Insets::ZERO,
            border: Insets::ZERO,
            border_color: None,
            background: None,
            width: None,
            height: None,
            #[cfg(feature = "flexbox")]
            flex_grow: 0,
            #[cfg(feature = "flexbox")]
            flex_basis: FlexBasis::Auto,
            specific: S::default(),
        }
    }
}

impl<S: Default, C> Style<S, C> {
    /// Derive a [`BoxStyle`] for layout.
    pub(crate) const fn box_style(&self) -> BoxStyle {
        BoxStyle {
            margin: self.margin,
            padding: self.padding,
            border: self.border,
            width: self.width,
            height: self.height,
        }
    }

    #[cfg(feature = "flexbox")]
    pub(crate) const fn flex_item_style(&self) -> FlexItemStyle {
        FlexItemStyle { flex_grow: self.flex_grow, flex_basis: self.flex_basis }
    }
}

impl<S: Default, C> core::ops::Deref for Style<S, C> {
    type Target = S;

    fn deref(&self) -> &Self::Target {
        &self.specific
    }
}

impl<S: Default, C> core::ops::DerefMut for Style<S, C> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.specific
    }
}

/// A blanket trait for elements that can be styled. Import [`StyledElement`] to use.
pub trait StyledElement: Sized {
    /// The pixel color used by this element.
    type Color: PixelColor;

    /// The specific style type for this element.
    type Specific: Default;

    /// Returns a reference to the element's specific style.
    fn style(&self) -> &Style<Self::Specific, Self::Color>;

    /// Returns a mutable reference to the element's specific style.
    fn style_mut(&mut self) -> &mut Style<Self::Specific, Self::Color>;

    /// Sets the padding using a CSS-like one-to-four-value inset shorthand.
    fn padding(mut self, padding: impl Into<Insets>) -> Self {
        self.style_mut().padding = padding.into();
        self
    }

    /// Sets the margin using a CSS-like one-to-four-value inset shorthand.
    fn margin(mut self, margin: impl Into<Insets>) -> Self {
        self.style_mut().margin = margin.into();
        self
    }

    /// Sets the background color of the element.
    fn background(mut self, color: Self::Color) -> Self {
        self.style_mut().background = Some(color);
        self
    }

    /// Shorthand for [`Self::background`].
    fn bg(self, color: Self::Color) -> Self {
        self.background(color)
    }

    /// Sets the border widths using a CSS-like one-to-four-value inset shorthand.
    fn border(mut self, border: impl Into<Insets>) -> Self {
        self.style_mut().border = border.into();
        self
    }

    /// Sets the size of the element's border box.
    fn size(mut self, size: Size) -> Self {
        self.style_mut().width = Some(size.width);
        self.style_mut().height = Some(size.height);
        self
    }

    /// Sets the width of the element's border box.
    fn width(mut self, width: u32) -> Self {
        self.style_mut().width = Some(width);
        self
    }

    /// Sets the height of the element's border box.
    fn height(mut self, height: u32) -> Self {
        self.style_mut().height = Some(height);
        self
    }

    /// Sets the border color of the element.
    fn border_color(mut self, color: Self::Color) -> Self {
        self.style_mut().border_color = Some(color);
        self
    }

    /// Sets the flex grow factor of the element.
    #[cfg(feature = "flexbox")]
    fn flex_grow(mut self, factor: u16) -> Self {
        self.style_mut().flex_grow = factor;
        self
    }

    /// Sets the flex basis of the element.
    #[cfg(feature = "flexbox")]
    fn flex_basis(mut self, flex_basis: FlexBasis) -> Self {
        self.style_mut().flex_basis = flex_basis;
        self
    }

    /// Sets a zero flex basis and the given grow factor.
    #[cfg(feature = "flexbox")]
    fn flex(mut self, factor: u16) -> Self {
        self.style_mut().flex_grow = factor;
        self.style_mut().flex_basis = FlexBasis::Zero;
        self
    }
}

/// Direction or axis of the flex layout, either horizontally (row) or vertically (column).
#[derive(Default, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum FlexDirection {
    /// Horizontal axis (default).
    #[default]
    Row,
    /// Vertical axis.
    Column,
}

impl From<&'static str> for FlexDirection {
    fn from(value: &'static str) -> Self {
        match value {
            "row" => Self::Row,
            "column" => Self::Column,
            _ => panic!("invalid flex direction: {}", value),
        }
    }
}

/// Justification of the flex items along the main axis.
#[cfg(feature = "flexbox")]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum JustifyContent {
    /// Items are packed at the start of the main axis.
    #[default]
    Start,
    /// Items are packed at the end of the main axis.
    End,
    /// Items are centered along the main axis.
    Center,
    /// Items are packed with equal space between them, with the first item at the start and the
    /// last item at the end.
    SpaceBetween,
    /// Items are packed with equal space around them.
    SpaceAround,
    /// Items are packed with equal space evenly around them (including near the edges).
    SpaceEvenly,
}

#[cfg(feature = "flexbox")]
impl JustifyContent {
    /// Calculates the shift of an item along the main axis based on the justify content strategy,
    /// distributed from the free space.
    pub(crate) const fn shift(&self, free: u32, index: u32, count: u32) -> u32 {
        match self {
            Self::End => free,
            Self::Center => free / 2,
            Self::SpaceBetween if count > 1 => Self::ratio(free, index, count - 1),
            Self::SpaceAround if count > 0 => Self::ratio(free, 2 * index + 1, 2 * count),
            Self::SpaceEvenly => Self::ratio(free, index + 1, count + 1),
            Self::Start | Self::SpaceBetween | Self::SpaceAround => 0,
        }
    }

    const fn ratio(space: u32, num: u32, denom: u32) -> u32 {
        ((space as u64 * num as u64) / denom as u64) as u32
    }
}

/// Alignment of the flex items along the cross axis (the axis perpendicular to the main axis).
/// Think of this as the justify-content equivalent for the cross axis.
#[cfg(feature = "flexbox")]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum AlignItems {
    /// Stretch to fill the container's cross size (default).
    #[default]
    Stretch,
    /// Align items at the start of the cross axis.
    Start,
    /// Align items at the end of the cross axis.
    End,
    /// Align items at the center of the cross axis.
    Center,
}

#[cfg(feature = "flexbox")]
impl AlignItems {
    /// Calculates the shift of an item along the cross axis based on the align items strategy,
    /// distributed from the free space.
    pub(crate) const fn shift(&self, free: u32) -> u32 {
        match self {
            Self::Stretch | Self::Start => 0,
            Self::End => free,
            Self::Center => free / 2,
        }
    }

    pub(crate) const fn is_stretch(&self) -> bool {
        matches!(self, Self::Stretch)
    }
}

/// Flexbox layout properties.
#[derive(PartialEq, Eq)]
pub(crate) struct FlexLayout {
    /// Direction of the flex layout, either horizontally (row) or vertically (column).
    pub direction: FlexDirection,
    /// Spacing between flex items.
    pub gap: Size,
    #[cfg(feature = "flexbox")]
    /// Justification of the flex items along the main axis.
    pub justify_content: JustifyContent,
    #[cfg(feature = "flexbox")]
    /// Alignment of the flex items along the cross axis.
    pub align_items: AlignItems,
}

impl From<DivStyle> for FlexLayout {
    fn from(style: DivStyle) -> Self {
        Self {
            direction: style.direction,
            gap: style.gap,
            #[cfg(feature = "flexbox")]
            justify_content: style.justify_content,
            #[cfg(feature = "flexbox")]
            align_items: style.align_items,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn css_shorthands_expand_in_trbl_order() {
        assert_eq!(Insets::from(10), Insets::new(10, 10, 10, 10));
        assert_eq!(Insets::from((4, 8)), Insets::new(4, 8, 4, 8));
        assert_eq!(Insets::from((4, 8, 12)), Insets::new(4, 8, 12, 8));
        assert_eq!(Insets::from((4, 8, 12, 16)), Insets::new(4, 8, 12, 16));
    }

    #[test]
    fn typed_unsigned_inputs_are_supported() {
        assert_eq!(Insets::from(3_u32), Insets::uniform(3));
        assert_eq!(Insets::from((1_usize, 2, 3)), Insets::new(1, 2, 3, 2));
    }

    #[test]
    fn usize_conversion_saturates() {
        assert_eq!(Insets::from(usize::MAX), Insets::uniform(u32::MAX));
    }

    #[test]
    #[should_panic(expected = "insets cannot be negative")]
    fn signed_conversion_rejects_negative_values() {
        let _ = Insets::from((1, -2));
    }

    #[test]
    fn inset_arithmetic_saturates() {
        let insets = Insets::new(u32::MAX, u32::MAX, 3, 4);

        assert_eq!(insets.horizontal(), u32::MAX);
        assert_eq!(insets.vertical(), u32::MAX);
        assert_eq!(
            insets.saturating_add(Insets::new(1, 2, u32::MAX, u32::MAX)),
            Insets::new(u32::MAX, u32::MAX, u32::MAX, u32::MAX),
        );
    }
}