masonry 0.4.0

Traits and types of the Masonry toolkit.
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
// Copyright 2019 the Xilem Authors and the Druid Authors
// SPDX-License-Identifier: Apache-2.0

//! A widget with predefined size.

use std::any::TypeId;

use accesskit::{Node, Role};
use masonry_core::core::HasProperty;
use tracing::{Span, trace_span, warn};
use vello::Scene;
use vello::kurbo::{Point, Size};

use crate::core::{
    AccessCtx, BoxConstraints, ChildrenIds, LayoutCtx, NewWidget, NoAction, PaintCtx,
    PropertiesMut, PropertiesRef, RegisterCtx, UpdateCtx, Widget, WidgetId, WidgetMut, WidgetPod,
};
use crate::properties::types::Length;
use crate::properties::{Background, BorderColor, BorderWidth, CornerRadius, Padding};
use crate::util::{fill, include_screenshot, stroke};

/// A widget with predefined size.
///
/// If given a child, this widget forces its child to have a specific width and/or height
/// (assuming values are permitted by this widget's parent). If either the width or height is not
/// set, this widget will size itself to match the child's size in that dimension.
///
/// If not given a child, `SizedBox` will try to size itself as close to the specified height
/// and width as possible given the parent's constraints. If height or width is not set,
/// it will be treated as zero.
///
#[doc = include_screenshot!("sized_box_label_box_with_outer_padding.png", "Box with blue border, pink background and a child label.")]
pub struct SizedBox {
    child: Option<WidgetPod<dyn Widget>>,
    // TODO - Right now width and height can't be stored as Length values,
    // because they use f64::INFINITY as a sentinel value when using the `expand()` methods.
    // Using float infinity as a sentinel value is somewhat of an anti-pattern and should be removed.
    width: Option<f64>,
    height: Option<f64>,
}

// --- MARK: BUILDERS
impl SizedBox {
    /// Construct container with child, and both width and height not set.
    pub fn new(child: NewWidget<impl Widget + ?Sized>) -> Self {
        Self {
            child: Some(child.erased().to_pod()),
            width: None,
            height: None,
        }
    }

    /// Construct container without child, and both width and height not set.
    ///
    /// If the widget is unchanged, it will render nothing, which can be useful if you want to draw a
    /// widget some of the time.
    #[doc(alias = "null")]
    pub fn empty() -> Self {
        Self {
            child: None,
            width: None,
            height: None,
        }
    }

    /// Set container's width.
    pub fn width(mut self, width: Length) -> Self {
        self.width = Some(width.get());
        self
    }

    /// Set container's height.
    pub fn height(mut self, height: Length) -> Self {
        self.height = Some(height.get());
        self
    }

    /// Set container's width and height.
    pub fn size(mut self, width: Length, height: Length) -> Self {
        self.width = Some(width.get());
        self.height = Some(height.get());
        self
    }

    /// Expand container to fit the parent.
    ///
    /// Only call this method if you want your widget to occupy all available
    /// space. If you only care about expanding in one of width or height, use
    /// [`expand_width`] or [`expand_height`] instead.
    ///
    /// [`expand_height`]: Self::expand_height
    /// [`expand_width`]: Self::expand_width
    pub fn expand(mut self) -> Self {
        // TODO - Using infinity in layout is a code smell.
        // Rework these methods.
        self.width = Some(f64::INFINITY);
        self.height = Some(f64::INFINITY);
        self
    }

    /// Expand the container on the x-axis.
    ///
    /// This will force the child to have maximum width.
    pub fn expand_width(mut self) -> Self {
        self.width = Some(f64::INFINITY);
        self
    }

    /// Expand the container on the y-axis.
    ///
    /// This will force the child to have maximum height.
    pub fn expand_height(mut self) -> Self {
        self.height = Some(f64::INFINITY);
        self
    }

    /// Set the width directly. Intended for toolkits abstracting over `SizedBox`.
    ///
    /// If `Some`, the value should be non-negative and not NaN.
    pub fn raw_width(mut self, value: Option<f64>) -> Self {
        self.width = value;
        self
    }

    /// Set the height directly. Intended for toolkits abstracting over `SizedBox`.
    ///
    /// If `Some`, the value should be non-negative and not NaN.
    pub fn raw_height(mut self, value: Option<f64>) -> Self {
        self.height = value;
        self
    }
}

// --- MARK: WIDGETMUT
impl SizedBox {
    /// Give this container a child widget.
    ///
    /// If this container already has a child, it will be overwritten.
    pub fn set_child(this: &mut WidgetMut<'_, Self>, child: NewWidget<impl Widget + ?Sized>) {
        if let Some(child) = this.widget.child.take() {
            this.ctx.remove_child(child);
        }
        this.widget.child = Some(child.erased().to_pod());
        this.ctx.children_changed();
        this.ctx.request_layout();
    }

    /// Remove the child widget.
    ///
    /// (If this widget has no child, this method does nothing.)
    pub fn remove_child(this: &mut WidgetMut<'_, Self>) {
        if let Some(child) = this.widget.child.take() {
            this.ctx.remove_child(child);
        }
    }

    /// Set container's width.
    pub fn set_width(this: &mut WidgetMut<'_, Self>, width: Length) {
        this.widget.width = Some(width.get());
        this.ctx.request_layout();
    }

    /// Set container's height.
    pub fn set_height(this: &mut WidgetMut<'_, Self>, height: Length) {
        this.widget.height = Some(height.get());
        this.ctx.request_layout();
    }

    /// Set container's width and height.
    pub fn set_size(this: &mut WidgetMut<'_, Self>, width: Length, height: Length) {
        this.widget.width = Some(width.get());
        this.widget.height = Some(height.get());
        this.ctx.request_layout();
    }

    /// Unset container's width.
    pub fn unset_width(this: &mut WidgetMut<'_, Self>) {
        this.widget.width = None;
        this.ctx.request_layout();
    }

    /// Unset container's height.
    pub fn unset_height(this: &mut WidgetMut<'_, Self>) {
        this.widget.height = None;
        this.ctx.request_layout();
    }

    /// Set the width directly. Intended for toolkits abstracting over `SizedBox`.
    ///
    /// If `Some`, the value should be non-negative and not NaN.
    pub fn set_raw_width(this: &mut WidgetMut<'_, Self>, value: Option<f64>) {
        this.widget.width = value;
        this.ctx.request_layout();
    }

    /// Set the height directly. Intended for toolkits abstracting over `SizedBox`.
    ///
    /// If `Some`, the value should be non-negative and not NaN.
    pub fn set_raw_height(this: &mut WidgetMut<'_, Self>, value: Option<f64>) {
        this.widget.height = value;
        this.ctx.request_layout();
    }

    /// Get mutable reference to the child widget, if any.
    pub fn child_mut<'t>(this: &'t mut WidgetMut<'_, Self>) -> Option<WidgetMut<'t, dyn Widget>> {
        let child = this.widget.child.as_mut()?;
        Some(this.ctx.get_mut(child))
    }
}

// --- MARK: INTERNALS
impl SizedBox {
    fn child_constraints(&self, bc: &BoxConstraints) -> BoxConstraints {
        // if we don't have a width/height, we don't change that axis.
        // if we have a width/height, we clamp it on that axis.
        let (min_width, max_width) = match self.width {
            Some(width) => {
                let w = width.max(bc.min().width).min(bc.max().width);
                (w, w)
            }
            None => (bc.min().width, bc.max().width),
        };

        let (min_height, max_height) = match self.height {
            Some(height) => {
                let h = height.max(bc.min().height).min(bc.max().height);
                (h, h)
            }
            None => (bc.min().height, bc.max().height),
        };

        BoxConstraints::new(
            Size::new(min_width, min_height),
            Size::new(max_width, max_height),
        )
    }
}

impl HasProperty<Background> for SizedBox {}
impl HasProperty<BorderColor> for SizedBox {}
impl HasProperty<BorderWidth> for SizedBox {}
impl HasProperty<CornerRadius> for SizedBox {}
impl HasProperty<Padding> for SizedBox {}

// --- MARK: IMPL WIDGET
impl Widget for SizedBox {
    type Action = NoAction;

    fn accepts_pointer_interaction(&self) -> bool {
        false
    }

    fn register_children(&mut self, ctx: &mut RegisterCtx<'_>) {
        if let Some(ref mut child) = self.child {
            ctx.register_child(child);
        }
    }

    fn property_changed(&mut self, ctx: &mut UpdateCtx<'_>, property_type: TypeId) {
        Background::prop_changed(ctx, property_type);
        BorderColor::prop_changed(ctx, property_type);
        BorderWidth::prop_changed(ctx, property_type);
        CornerRadius::prop_changed(ctx, property_type);
        Padding::prop_changed(ctx, property_type);
    }

    fn layout(
        &mut self,
        ctx: &mut LayoutCtx<'_>,
        props: &mut PropertiesMut<'_>,
        bc: &BoxConstraints,
    ) -> Size {
        let border = props.get::<BorderWidth>();
        let padding = props.get::<Padding>();

        let bc = self.child_constraints(bc);
        let bc = border.layout_down(bc);
        let bc = padding.layout_down(bc);

        let origin = Point::ORIGIN;
        let origin = border.place_down(origin);
        let origin = padding.place_down(origin);

        let mut size;
        match self.child.as_mut() {
            Some(child) => {
                size = ctx.run_layout(child, &bc);
                ctx.place_child(child, origin);
            }
            None => {
                size = (self.width.unwrap_or(0.0), self.height.unwrap_or(0.0)).into();
                size = bc.constrain(size);
            }
        };

        let (size, _) = padding.layout_up(size, 0.);
        let (size, _) = border.layout_up(size, 0.);

        // TODO - figure out paint insets
        // TODO - figure out baseline offset

        if size.width.is_infinite() {
            warn!("SizedBox is returning an infinite width.");
        }
        if size.height.is_infinite() {
            warn!("SizedBox is returning an infinite height.");
        }

        size
    }

    fn paint(&mut self, ctx: &mut PaintCtx<'_>, props: &PropertiesRef<'_>, scene: &mut Scene) {
        let bg = props.get::<Background>();
        let border_width = props.get::<BorderWidth>();
        let border_color = props.get::<BorderColor>();
        let corner_radius = props.get::<CornerRadius>();

        let bg_rect = border_width.bg_rect(ctx.size(), corner_radius);
        let border_rect = border_width.border_rect(ctx.size(), corner_radius);

        let brush = bg.get_peniko_brush_for_rect(bg_rect.rect());
        fill(scene, &bg_rect, &brush);
        stroke(scene, &border_rect, border_color.color, border_width.width);
    }

    fn accessibility_role(&self) -> Role {
        Role::GenericContainer
    }

    fn accessibility(
        &mut self,
        _ctx: &mut AccessCtx<'_>,
        _props: &PropertiesRef<'_>,
        _node: &mut Node,
    ) {
    }

    fn children_ids(&self) -> ChildrenIds {
        if let Some(child) = &self.child {
            ChildrenIds::from_slice(&[child.id()])
        } else {
            ChildrenIds::from_slice(&[])
        }
    }

    fn make_trace_span(&self, id: WidgetId) -> Span {
        trace_span!("SizedBox", id = id.trace())
    }
}

// --- MARK: TESTS
#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::Properties;
    use crate::palette;
    use crate::properties::types::{AsUnit, Gradient, UnitPoint};
    use crate::testing::{TestHarness, assert_failing_render_snapshot, assert_render_snapshot};
    use crate::theme::default_property_set;
    use crate::widgets::Label;

    // TODO - Add WidgetMut tests

    #[test]
    fn expand() {
        let expand = SizedBox::new(Label::new("hello!").with_auto_id()).expand();
        let bc = BoxConstraints::tight(Size::new(400., 400.)).loosen();
        let child_bc = expand.child_constraints(&bc);
        assert_eq!(child_bc.min(), Size::new(400., 400.,));
    }

    #[test]
    fn no_width() {
        let expand = SizedBox::new(Label::new("hello!").with_auto_id()).height(200.px());
        let bc = BoxConstraints::tight(Size::new(400., 400.)).loosen();
        let child_bc = expand.child_constraints(&bc);
        assert_eq!(child_bc.min(), Size::new(0., 200.,));
        assert_eq!(child_bc.max(), Size::new(400., 200.,));
    }

    #[test]
    fn empty_box() {
        let mut box_props = Properties::new();
        box_props.insert(BorderColor::new(palette::css::BLUE));
        box_props.insert(BorderWidth::all(5.0));
        box_props.insert(CornerRadius::all(5.0));

        let widget = SizedBox::empty()
            .width(20.px())
            .height(20.px())
            .with_props(box_props);

        let window_size = Size::new(100.0, 100.0);
        let mut harness =
            TestHarness::create_with_size(default_property_set(), widget, window_size);

        assert_render_snapshot!(harness, "sized_box_empty_box");
    }

    #[test]
    fn label_box_no_size() {
        let mut box_props = Properties::new();
        box_props.insert(BorderColor::new(palette::css::BLUE));
        box_props.insert(BorderWidth::all(5.0));
        box_props.insert(CornerRadius::all(5.0));

        let widget = SizedBox::new(Label::new("hello").with_auto_id()).with_props(box_props);

        let window_size = Size::new(100.0, 100.0);
        let mut harness =
            TestHarness::create_with_size(default_property_set(), widget, window_size);

        assert_render_snapshot!(harness, "sized_box_label_box_no_size");
    }

    #[test]
    fn label_box_with_size() {
        let mut box_props = Properties::new();
        box_props.insert(BorderColor::new(palette::css::BLUE));
        box_props.insert(BorderWidth::all(5.0));
        box_props.insert(CornerRadius::all(5.0));

        let widget = SizedBox::new(Label::new("hello").with_auto_id())
            .width(20.px())
            .height(20.px())
            .with_props(box_props);

        let window_size = Size::new(100.0, 100.0);
        let mut harness =
            TestHarness::create_with_size(default_property_set(), widget, window_size);

        assert_render_snapshot!(harness, "sized_box_label_box_with_size");
    }

    #[test]
    fn label_box_with_padding() {
        let mut box_props = Properties::new();
        box_props.insert(BorderColor::new(palette::css::BLUE));
        box_props.insert(BorderWidth::all(5.0));
        box_props.insert(CornerRadius::all(5.0));
        box_props.insert(Padding::from_vh(15., 10.));

        let widget = SizedBox::new(Label::new("hello").with_auto_id()).with_props(box_props);

        let window_size = Size::new(100.0, 100.0);
        let mut harness =
            TestHarness::create_with_size(default_property_set(), widget, window_size);

        assert_render_snapshot!(harness, "sized_box_label_box_with_padding");
    }

    #[test]
    fn label_box_with_solid_background() {
        let mut box_props = Properties::new();
        box_props.insert(Background::Color(palette::css::PLUM));

        let widget = SizedBox::new(Label::new("hello").with_auto_id())
            .width(20.px())
            .height(20.px())
            .with_props(box_props);

        let window_size = Size::new(100.0, 100.0);
        let mut harness =
            TestHarness::create_with_size(default_property_set(), widget, window_size);

        assert_render_snapshot!(harness, "sized_box_label_box_with_solid_background");
    }

    #[test]
    fn empty_box_with_gradient_background() {
        let mut box_props = Properties::new();

        let gradient = Gradient::new_linear(2.0).with_stops([
            palette::css::WHITE,
            palette::css::BLACK,
            palette::css::RED,
            palette::css::GREEN,
            palette::css::WHITE,
        ]);
        box_props.insert(Background::Gradient(gradient));
        box_props.insert(BorderColor::new(palette::css::LIGHT_SKY_BLUE));
        box_props.insert(BorderWidth::all(5.0));
        box_props.insert(CornerRadius::all(10.0));

        let widget = SizedBox::empty()
            .width(20.px())
            .height(20.px())
            .with_props(box_props);

        let window_size = Size::new(100.0, 100.0);
        let mut harness =
            TestHarness::create_with_size(default_property_set(), widget, window_size);

        assert_render_snapshot!(harness, "sized_box_empty_box_with_gradient_background");
    }

    #[test]
    fn radial_gradient_background() {
        let mut box_props = Properties::new();

        let gradient = Gradient::new_radial(UnitPoint::CENTER).with_stops([
            palette::css::WHITE,
            palette::css::BLACK,
            palette::css::RED,
            palette::css::GREEN,
            palette::css::WHITE,
        ]);
        box_props.insert(Background::Gradient(gradient));
        box_props.insert(BorderColor::new(palette::css::LIGHT_SKY_BLUE));
        box_props.insert(BorderWidth::all(5.0));
        box_props.insert(CornerRadius::all(10.0));

        let widget = SizedBox::empty()
            .width(20.px())
            .height(20.px())
            .with_props(box_props);

        let window_size = Size::new(100.0, 100.0);
        let mut harness =
            TestHarness::create_with_size(default_property_set(), widget, window_size);

        assert_render_snapshot!(harness, "sized_box_radial_gradient_background");
    }

    #[test]
    fn sweep_gradient_background() {
        let mut box_props = Properties::new();

        let gradient = Gradient::new_full_sweep(UnitPoint::CENTER, 0.).with_stops([
            palette::css::WHITE,
            palette::css::BLACK,
            palette::css::RED,
            palette::css::GREEN,
            palette::css::WHITE,
        ]);
        box_props.insert(Background::Gradient(gradient));
        box_props.insert(BorderColor::new(palette::css::LIGHT_SKY_BLUE));
        box_props.insert(BorderWidth::all(5.0));
        box_props.insert(CornerRadius::all(10.0));

        let widget = SizedBox::empty()
            .width(20.px())
            .height(20.px())
            .with_props(box_props);

        let window_size = Size::new(100.0, 100.0);
        let mut harness =
            TestHarness::create_with_size(default_property_set(), widget, window_size);

        assert_render_snapshot!(harness, "sized_box_sweep_gradient_background");
    }

    #[test]
    fn label_box_with_padding_and_background() {
        let mut box_props = Properties::new();
        box_props.insert(Background::Color(palette::css::PLUM));
        box_props.insert(BorderColor::new(palette::css::LIGHT_SKY_BLUE));
        box_props.insert(BorderWidth::all(5.0));
        box_props.insert(Padding::all(25.));

        let widget = SizedBox::new(Label::new("hello").with_auto_id())
            .width(20.px())
            .height(20.px())
            .with_props(box_props);

        let window_size = Size::new(100.0, 100.0);
        let mut harness =
            TestHarness::create_with_size(default_property_set(), widget, window_size);

        assert_render_snapshot!(harness, "sized_box_label_box_with_background_and_padding");
    }

    // --- MARK: INVALID SCREENSHOT TESTS

    #[test]
    fn invalid_screenshot() {
        // Copy-pasted from empty_box
        let mut box_props = Properties::new();
        box_props.insert(BorderColor::new(palette::css::BLUE));
        box_props.insert(BorderWidth::all(5.0));
        box_props.insert(CornerRadius::all(5.0));

        // This is the difference
        box_props.insert(BorderWidth::all(5.2));

        let widget = SizedBox::empty()
            .width(20.px())
            .height(20.px())
            .with_props(box_props);

        let window_size = Size::new(100.0, 100.0);
        let mut harness =
            TestHarness::create_with_size(default_property_set(), widget, window_size);

        assert_failing_render_snapshot!(harness, "sized_box_empty_box");
    }
}