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
// Copyright 2019 the Xilem Authors and the Druid Authors
// SPDX-License-Identifier: Apache-2.0

//! A label widget.

use std::any::TypeId;
use std::mem::Discriminant;

use accesskit::{Node, NodeId, Role};
use masonry_core::core::{HasProperty, NoAction};
use parley::{Layout, LayoutAccessibility};
use tracing::{Span, trace_span};
use vello::Scene;
use vello::kurbo::{Affine, Point, Size};
use vello::peniko::BlendMode;

use crate::core::{
    AccessCtx, ArcStr, BoxConstraints, BrushIndex, ChildrenIds, LayoutCtx, PaintCtx, PropertiesMut,
    PropertiesRef, RegisterCtx, StyleProperty, StyleSet, Update, UpdateCtx, Widget, WidgetId,
    WidgetMut, render_text,
};
use crate::properties::{ContentColor, DisabledContentColor, LineBreaking, Padding};
use crate::theme::default_text_styles;
use crate::util::{debug_panic, include_screenshot};
use crate::{TextAlign, TextAlignOptions, theme};

/// A widget displaying non-interactive text.
///
/// This is useful for creating interactive widgets which internally
/// need support for displaying text, such as a button.
///
/// You can customize the look of this label with the
/// [`Padding`], [`LineBreaking`], [`ContentColor`] and [`DisabledContentColor`] properties.
///
#[doc = include_screenshot!("label_styled_label.png", "Styled label.")]
pub struct Label {
    text_layout: Layout<BrushIndex>,
    accessibility: LayoutAccessibility,

    text: ArcStr,
    styles: StyleSet,
    /// Whether `text` or `styles` has been updated since `text_layout` was created.
    ///
    /// If they have, the layout needs to be recreated.
    styles_changed: bool,

    text_alignment: TextAlign,
    /// Whether the text alignment needs to be re-computed.
    needs_text_alignment: bool,
    /// How much width was available during last layout.
    last_available_width: Option<f32>,
    /// The value of `max_advance` when this layout was last calculated.
    ///
    /// If it has changed, we need to re-perform line-breaking.
    last_max_advance: Option<f32>,

    /// Whether to hint whilst drawing the text.
    ///
    /// Should be disabled whilst an animation involving this label is ongoing.
    // TODO: What classes of animations?
    hint: bool,
}

// --- MARK: BUILDERS
impl Label {
    /// Create a new label with the given text.
    ///
    // This is written out fully to appease rust-analyzer; StyleProperty is imported but not recognised.
    /// To change the font size, use `with_style`, setting [`StyleProperty::FontSize`](parley::StyleProperty::FontSize).
    pub fn new(text: impl Into<ArcStr>) -> Self {
        let mut styles = StyleSet::new(theme::TEXT_SIZE_NORMAL);
        default_text_styles(&mut styles);
        Self {
            text_layout: Layout::new(),
            accessibility: LayoutAccessibility::default(),
            text: text.into(),
            styles,
            styles_changed: true,
            text_alignment: TextAlign::Start,
            needs_text_alignment: true,
            last_available_width: None,
            last_max_advance: None,
            hint: true,
        }
    }

    /// Get the current text of this label.
    ///
    /// To update the text of an active label, use [`set_text`](Self::set_text).
    pub fn text(&self) -> &ArcStr {
        &self.text
    }

    /// Set a style property for the new label.
    ///
    /// Setting [`StyleProperty::Brush`](parley::StyleProperty::Brush) is not supported.
    /// Use [`ContentColor`] and [`DisabledContentColor`] properties instead.
    ///
    /// To set a style property on an active label, use [`insert_style`](Self::insert_style).
    pub fn with_style(mut self, property: impl Into<StyleProperty>) -> Self {
        self.insert_style_inner(property.into());
        self
    }

    /// Set a style property for the new label, returning the old value.
    ///
    /// Most users should prefer [`with_style`](Self::with_style) instead.
    pub fn try_with_style(
        mut self,
        property: impl Into<StyleProperty>,
    ) -> (Self, Option<StyleProperty>) {
        let old = self.insert_style_inner(property.into());
        (self, old)
    }

    /// Set the alignment of the text.
    ///
    /// Text alignment might have unexpected results when the label has no horizontal constraints.
    /// To modify this on an active label, use [`set_text_alignment`](Self::set_text_alignment).
    pub fn with_text_alignment(mut self, text_alignment: TextAlign) -> Self {
        self.text_alignment = text_alignment;
        self
    }

    /// Set whether [hinting](https://en.wikipedia.org/wiki/Font_hinting) will be used for this label.
    ///
    /// Hinting is a process where text is drawn "snapped" to pixel boundaries to improve fidelity.
    /// The default is true, i.e. hinting is enabled by default.
    ///
    /// This should be set to false if the label will be animated at creation.
    /// The kinds of relevant animations include changing variable font parameters,
    /// translating or scaling.
    /// Failing to do so will likely lead to an unpleasant shimmering effect, as different parts of the
    /// text "snap" at different times.
    ///
    /// To modify this on an active label, use [`set_hint`](Self::set_hint).
    // TODO: Should we tell each widget if smooth scrolling is ongoing so they can disable their hinting?
    // Alternatively, we should automate disabling hinting at the Vello layer when composing.
    pub fn with_hint(mut self, hint: bool) -> Self {
        self.hint = hint;
        self
    }

    /// Shared logic between `with_style` and `insert_style`
    fn insert_style_inner(&mut self, property: StyleProperty) -> Option<StyleProperty> {
        if let StyleProperty::Brush(idx @ BrushIndex(1..))
        | StyleProperty::UnderlineBrush(Some(idx @ BrushIndex(1..)))
        | StyleProperty::StrikethroughBrush(Some(idx @ BrushIndex(1..))) = &property
        {
            debug_panic!(
                "Can't set a non-zero brush index ({idx:?}) on a `Label`, as it only supports global styling."
            );
        }
        self.styles.insert(property)
    }
}

// --- MARK: WIDGETMUT
impl Label {
    // Note: These docs are lazy, but also have a decreased likelihood of going out of date.
    /// The runtime equivalent of [`with_style`](Self::with_style).
    ///
    /// Setting [`StyleProperty::Brush`](parley::StyleProperty::Brush) is not supported.
    /// Use [`ContentColor`] and [`DisabledContentColor`] properties instead.
    pub fn insert_style(
        this: &mut WidgetMut<'_, Self>,
        property: impl Into<StyleProperty>,
    ) -> Option<StyleProperty> {
        let old = this.widget.insert_style_inner(property.into());

        this.widget.styles_changed = true;
        this.ctx.request_layout();
        old
    }

    /// Keep only the styles for which `f` returns true.
    ///
    /// Styles which are removed return to Parley's default values.
    /// In most cases, these are the defaults for this widget.
    ///
    /// Of note, behaviour is unspecified for unsetting the [`FontSize`](parley::StyleProperty::FontSize).
    pub fn retain_styles(this: &mut WidgetMut<'_, Self>, f: impl FnMut(&StyleProperty) -> bool) {
        this.widget.styles.retain(f);

        this.widget.styles_changed = true;
        this.ctx.request_layout();
    }

    /// Remove the style with the discriminant `property`.
    ///
    /// To get the discriminant requires constructing a valid `StyleProperty` for the
    /// the desired property and passing it to [`core::mem::discriminant`].
    /// Getting this discriminant is usually possible in a `const` context.
    ///
    /// Styles which are removed return to Parley's default values.
    /// In most cases, these are the defaults for this widget.
    ///
    /// Of note, behaviour is unspecified for unsetting the [`FontSize`](parley::StyleProperty::FontSize).
    pub fn remove_style(
        this: &mut WidgetMut<'_, Self>,
        property: Discriminant<StyleProperty>,
    ) -> Option<StyleProperty> {
        let old = this.widget.styles.remove(property);

        this.widget.styles_changed = true;
        this.ctx.request_layout();
        old
    }

    /// Replace the text of this widget.
    pub fn set_text(this: &mut WidgetMut<'_, Self>, new_text: impl Into<ArcStr>) {
        this.widget.text = new_text.into();

        this.widget.styles_changed = true;
        this.ctx.request_layout();
    }

    /// The runtime equivalent of [`with_text_alignment`](Self::with_text_alignment).
    pub fn set_text_alignment(this: &mut WidgetMut<'_, Self>, text_alignment: TextAlign) {
        this.widget.text_alignment = text_alignment;

        this.widget.needs_text_alignment = true;
        this.ctx.request_layout();
    }

    /// The runtime equivalent of [`with_hint`](Self::with_hint).
    pub fn set_hint(this: &mut WidgetMut<'_, Self>, hint: bool) {
        this.widget.hint = hint;
        this.ctx.request_paint_only();
    }
}

impl HasProperty<ContentColor> for Label {}
impl HasProperty<DisabledContentColor> for Label {}
impl HasProperty<LineBreaking> for Label {}

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

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

    fn register_children(&mut self, _ctx: &mut RegisterCtx<'_>) {}

    fn property_changed(&mut self, ctx: &mut UpdateCtx<'_>, property_type: TypeId) {
        LineBreaking::prop_changed(ctx, property_type);
        ContentColor::prop_changed(ctx, property_type);
        DisabledContentColor::prop_changed(ctx, property_type);
        Padding::prop_changed(ctx, property_type);
    }

    fn update(&mut self, ctx: &mut UpdateCtx<'_>, _props: &mut PropertiesMut<'_>, event: &Update) {
        match event {
            Update::DisabledChanged(_) => {
                ctx.request_paint_only();
            }
            _ => {}
        }
    }

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

        let bc = padding.layout_down(*bc);

        let available_width = Some(bc.max().width as f32);
        if available_width != self.last_available_width {
            self.last_available_width = available_width;
            self.needs_text_alignment = true;
        }

        let max_advance = if line_break_mode == LineBreaking::WordWrap {
            available_width
        } else {
            None
        };
        let styles_changed = self.styles_changed || ctx.fonts_changed();
        if styles_changed {
            let (font_ctx, layout_ctx) = ctx.text_contexts();
            // TODO: Should we use a different scale?
            // See https://github.com/linebender/xilem/issues/1264
            let mut builder = layout_ctx.ranged_builder(font_ctx, &self.text, 1.0, true);
            for prop in self.styles.inner().values() {
                builder.push_default(prop.to_owned());
            }
            builder.build_into(&mut self.text_layout, &self.text);
            self.styles_changed = false;
        }

        if max_advance != self.last_max_advance || styles_changed {
            self.text_layout.break_all_lines(max_advance);
            self.last_max_advance = max_advance;
            self.needs_text_alignment = true;
        }

        let alignment_width = if self.text_alignment == TextAlign::Start {
            self.text_layout.width()
        } else if let Some(width) = available_width {
            // We use the full available space to calculate text alignment and therefore
            // determine the widget's current width.
            //
            // As a special case, we don't do that if the alignment is to the start.
            // In theory, we should be passed down how our parent expects us to be aligned;
            // however that isn't currently handled.
            //
            // This does effectively mean that the widget takes up all the available space and
            // therefore doesn't play nicely with adjacent widgets unless `Start` alignment is used.
            //
            // The coherent way to have multiple items laid out on the same line and alignment is for them to
            // be inside the same text layout object "region".
            width
        } else {
            // TODO: Warn on the rising edge of entering this state for this widget?
            self.text_layout.width()
        };
        if self.needs_text_alignment {
            self.text_layout.align(
                Some(alignment_width),
                self.text_alignment,
                TextAlignOptions::default(),
            );
            self.needs_text_alignment = false;
        }

        let size = Size::new(alignment_width.into(), self.text_layout.height().into());
        let size = bc.constrain(size);
        let (size, baseline) = padding.layout_up(size, 0.);
        ctx.set_baseline_offset(baseline);
        size
    }

    fn paint(&mut self, ctx: &mut PaintCtx<'_>, props: &PropertiesRef<'_>, scene: &mut Scene) {
        let padding = *props.get::<Padding>();
        let line_break_mode = *props.get::<LineBreaking>();

        if line_break_mode == LineBreaking::Clip {
            let clip_rect = ctx.size().to_rect();
            scene.push_layer(BlendMode::default(), 1., Affine::IDENTITY, &clip_rect);
        }
        let text_origin = padding.place_down(Point::ZERO).to_vec2();
        let transform = Affine::translate(text_origin);

        let text_color = if ctx.is_disabled() {
            &props.get::<DisabledContentColor>().0
        } else {
            props.get::<ContentColor>()
        };

        render_text(
            scene,
            transform,
            &self.text_layout,
            &[text_color.color.into()],
            self.hint,
        );

        if line_break_mode == LineBreaking::Clip {
            scene.pop_layer();
        }
    }

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

    fn accessibility(
        &mut self,
        ctx: &mut AccessCtx<'_>,
        props: &PropertiesRef<'_>,
        node: &mut Node,
    ) {
        let padding = *props.get::<Padding>();

        let text_origin = padding.place_down(Point::ZERO).to_vec2();
        self.accessibility.build_nodes(
            self.text.as_ref(),
            &self.text_layout,
            ctx.tree_update(),
            node,
            || NodeId::from(WidgetId::next()),
            text_origin.x,
            text_origin.y,
        );
    }

    fn children_ids(&self) -> ChildrenIds {
        ChildrenIds::new()
    }

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

    fn get_debug_text(&self) -> Option<String> {
        Some(self.text.to_string())
    }
}

// --- MARK: TESTS
#[cfg(test)]
mod tests {
    use parley::style::GenericFamily;
    use parley::{FontFamily, StyleProperty};

    use super::*;
    use crate::core::Properties;
    use crate::properties::types::CrossAxisAlignment;
    use crate::properties::types::{AsUnit, Length};
    use crate::testing::{TestHarness, assert_render_snapshot};
    use crate::theme::{ACCENT_COLOR, default_property_set};
    use crate::widgets::{Flex, SizedBox};

    #[test]
    fn simple_label() {
        let label = Label::new("Hello").with_auto_id();

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

        assert_render_snapshot!(harness, "label_hello");
    }

    #[test]
    fn styled_label() {
        let label = Label::new("The quick brown fox jumps over the lazy dog")
            .with_style(FontFamily::Generic(GenericFamily::Monospace))
            .with_style(StyleProperty::FontSize(20.0))
            .with_text_alignment(TextAlign::Center)
            .with_props(
                Properties::new()
                    .with(ContentColor::new(ACCENT_COLOR))
                    .with(LineBreaking::WordWrap),
            );

        let mut harness =
            TestHarness::create_with_size(default_property_set(), label, Size::new(200.0, 200.0));

        assert_render_snapshot!(harness, "label_styled_label");
    }

    #[test]
    fn underline_label() {
        let label = Label::new("Emphasis")
            .with_style(StyleProperty::Underline(true))
            .with_props(Properties::new().with(LineBreaking::WordWrap));

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

        assert_render_snapshot!(harness, "label_underline_label");
    }
    #[test]
    fn strikethrough_label() {
        let label = Label::new("Tpyo")
            .with_style(StyleProperty::Strikethrough(true))
            .with_style(StyleProperty::StrikethroughSize(Some(4.)))
            .with_props(Properties::new().with(LineBreaking::WordWrap));

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

        assert_render_snapshot!(harness, "label_strikethrough_label");
    }

    #[test]
    /// A wrapping label's text alignment should be respected, regardless of
    /// its parent's text alignment.
    fn label_text_alignment_flex() {
        fn base_label() -> Label {
            Label::new("Hello").with_style(StyleProperty::FontSize(20.0))
            //.with_props(Properties::new().with(LineBreaking::WordWrap))
        }
        let label1 = base_label().with_text_alignment(TextAlign::Start);
        let label2 = base_label().with_text_alignment(TextAlign::Center);
        let label3 = base_label().with_text_alignment(TextAlign::End);
        let label4 = base_label().with_text_alignment(TextAlign::Start);
        let label5 = base_label().with_text_alignment(TextAlign::Center);
        let label6 = base_label().with_text_alignment(TextAlign::End);
        let flex = Flex::column()
            .with_flex_child(label1.with_auto_id(), CrossAxisAlignment::Start)
            .with_flex_child(label2.with_auto_id(), CrossAxisAlignment::Start)
            .with_flex_child(label3.with_auto_id(), CrossAxisAlignment::Start)
            // Text alignment start is "overwritten" by CrossAxisAlignment::Center.
            .with_flex_child(label4.with_auto_id(), CrossAxisAlignment::Center)
            .with_flex_child(label5.with_auto_id(), CrossAxisAlignment::Center)
            .with_flex_child(label6.with_auto_id(), CrossAxisAlignment::Center)
            .with_gap(Length::ZERO)
            .with_auto_id();

        let mut harness =
            TestHarness::create_with_size(default_property_set(), flex, Size::new(200.0, 200.0));

        assert_render_snapshot!(harness, "label_label_alignment_flex");
    }

    #[test]
    fn line_break_modes() {
        let widget = Flex::column()
            .with_flex_spacer(1.0)
            .with_child(
                SizedBox::new(
                    Label::new("The quick brown fox jumps over the lazy dog")
                        .with_props(Properties::new().with(LineBreaking::WordWrap)),
                )
                .width(180.px())
                .with_auto_id(),
            )
            .with_spacer(20.px())
            .with_child(
                SizedBox::new(
                    Label::new("The quick brown fox jumps over the lazy dog")
                        .with_props(Properties::new().with(LineBreaking::Clip)),
                )
                .width(180.px())
                .with_auto_id(),
            )
            .with_spacer(20.px())
            .with_child(
                SizedBox::new(
                    Label::new("The quick brown fox jumps over the lazy dog")
                        .with_props(Properties::new().with(LineBreaking::Overflow)),
                )
                .width(180.px())
                .with_auto_id(),
            )
            .with_flex_spacer(1.0)
            .with_auto_id();

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

        assert_render_snapshot!(harness, "label_line_break_modes");
    }

    #[test]
    fn edit_label() {
        let image_1 = {
            let label = Label::new("The quick brown fox jumps over the lazy dog")
                .with_style(FontFamily::Generic(GenericFamily::Monospace))
                .with_style(StyleProperty::FontSize(20.0))
                .with_text_alignment(TextAlign::Center)
                .with_props(
                    Properties::new()
                        .with(ContentColor::new(ACCENT_COLOR))
                        .with(LineBreaking::WordWrap),
                );

            let mut harness =
                TestHarness::create_with_size(default_property_set(), label, Size::new(50.0, 50.0));

            harness.render()
        };

        let image_2 = {
            let label = Label::new("Hello world")
                .with_style(StyleProperty::FontSize(40.0))
                .with_auto_id();

            let mut harness =
                TestHarness::create_with_size(default_property_set(), label, Size::new(50.0, 50.0));

            harness.edit_root_widget(|mut label| {
                label.insert_prop(ContentColor::new(ACCENT_COLOR));
                label.insert_prop(LineBreaking::WordWrap);
                Label::set_text(&mut label, "The quick brown fox jumps over the lazy dog");
                Label::insert_style(&mut label, FontFamily::Generic(GenericFamily::Monospace));
                Label::insert_style(&mut label, StyleProperty::FontSize(20.0));
                Label::set_text_alignment(&mut label, TextAlign::Center);
            });

            harness.render()
        };

        // We don't use assert_eq because we don't want rich assert
        assert!(image_1 == image_2);
    }
}