bevy_pages 0.3.5

Upgrade your Bevy UI experience with XML and an extended widget collection.
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
use crate::element::ElementProps;
use crate::parser::AttributeMap;
use crate::parser::color::parse_color;
use crate::parser::values::{parse_attribute, parse_border_rect, parse_float};
use crate::parser::values::{parse_bool, parse_matches, parse_rect};
use crate::props::Properties;
use crate::systems::PageSystemSet;
use crate::widgets::Widget;
use bevy::app::{App, Update};
use bevy::asset::{AssetServer, Handle};
use bevy::color::Color;
use bevy::image::Image;
use bevy::math::Rect;
use bevy::prelude::{
    BorderRect, Changed, Entity, ImageNode, Interaction, IntoScheduleConfigs, NodeImageMode, Or,
    Query, Res, TextureSlicer, VisualBox, World,
};
use bevy::sprite::SliceScaleMode;
use bevy::ui::Val;
use roxmltree::Node;

fn update_props(
    assets: Res<AssetServer>,
    mut query: Query<
        (&Interaction, &Properties<ImageProps>, &mut ImageNode),
        Or<(Changed<Interaction>, Changed<Properties<ImageProps>>)>,
    >,
) {
    for (interaction, props, mut image_node) in &mut query {
        let props = match interaction {
            Interaction::Pressed => &props.click,
            Interaction::Hovered => &props.hover,
            Interaction::None => &props.default,
        };

        let image = props.src.fetch(&assets);

        crate::set_if_changed!(
            image_node.color, props.color;
            image_node.flip_x, props.flip_x;
            image_node.flip_y, props.flip_y;
            image_node.rect, props.rect;
            image_node.image_mode, props.mode => props.mode.clone();
            image_node.visual_box, props.visual_box;
            image_node.image, image;
        );
    }
}

/// The source of an [ImageWidget].
#[derive(Clone, Debug)]
pub enum ImageSource {
    /// Load the image from the given path via [AssetServer::load].
    Path(String),
    /// Directly use the given image handle.
    Handle(Handle<Image>),
}

impl ImageSource {
    /// Fetch the image handle from this source.
    ///
    /// This will load the image from the asset server if the source is a path.
    ///
    /// If the source is a handle, it will return the handle directly.
    pub fn fetch(&self, assets: &AssetServer) -> Handle<Image> {
        match self {
            ImageSource::Path(path) => assets.load(path),
            ImageSource::Handle(image) => image.clone(),
        }
    }
}

/// An image widget.
///
/// ## XML Usage
///
/// Build a new image widget using the `<Image />` tag.
///
/// ### Attributes
/// - `src = "<string>"`: The asset path to the actual image to display. Required.
/// - `color = "<color>"`: The color/tint of the image.
/// - `flip-x = "<bool>"`: Whether to flip the image horizontally.
/// - `flip-y = "<bool>"`: Whether to flip the image vertically.
/// - `rect = "<rect>"`: The rect to clip the image to.
/// - `mode = "<auto|sliced|tiled|stretch>"`: The layout mode to use for the image.
/// - `visual-box = "<padding|content|border>"`: The visual box of the image.
/// - `sliced-border = "<borderRect>"`: The border rect when `mode = "sliced"`.
/// - `sliced-center-scale-stretch = "<float>"`: The center scale when `mode = "sliced"` and `sliced-center-scale = "tile"`.
/// - `sliced-center-scale = "<stretch|tile>"`: The center scale when `mode = "sliced"`.
/// - `sliced-sides-scale-stretch = "<float>"`: The sides scale when `mode = "sliced"` and `sliced-sides-scale = "tile"`.
/// - `sliced-sides-scale = "<stretch|tile>"`: The sides scale when `mode = "sliced"`.
/// - `sliced-max-corner-scale = "<float>"`: The max corner scale when `mode = "sliced"`.
/// - `tiled-x = "<bool>"`: Whether to tile the image horizontally, when `mode = "tiled"`.
/// - `tiled-y = "<bool>"`: Whether to tile the image vertically, when `mode = "tiled"`.
/// - `tiled-stretch = "<float>"`: The stretch scale when `mode = "tiled"`.
///
/// All the attributes listed support state overrides.
///
/// ## Logic
///
/// Use [ImageProps] to control the image widget.
/// Use generic element events to implement custom behavior.
#[derive(Clone, Debug, Default)]
pub struct ImageWidget {
    props: Properties<ImageProps>,
}

impl Widget for ImageWidget {
    fn name() -> &'static str
    where
        Self: Sized,
    {
        "Image"
    }

    fn setup(&self, app: &mut App) {
        app.add_systems(Update, update_props.in_set(PageSystemSet));
    }

    fn parse(&mut self, _: &Node, attrs: &AttributeMap) -> Result<(), String>
    where
        Self: Sized,
    {
        let default = ImageProps::parse(attrs, None, &ImageProps::default())?;
        let hover = ImageProps::parse(attrs, Some("hover"), &default)?;
        let click = ImageProps::parse(attrs, Some("click"), &default)?;

        self.props = Properties {
            default,
            hover,
            click,
        };

        Ok(())
    }

    fn spawn(&self, entity: Entity, world: &mut World) -> Entity {
        let assets = world.resource::<AssetServer>();

        let props = &self.props.default;
        let image = ImageNode {
            color: props.color,
            image: props.src.fetch(assets),
            texture_atlas: None,
            flip_x: props.flip_x,
            flip_y: props.flip_y,
            rect: props.rect,
            image_mode: props.mode.clone(),
            visual_box: props.visual_box,
        };

        world.entity_mut(entity).insert((self.props.clone(), image));

        entity
    }

    fn apply_defaults(
        &self,
        attrs: &AttributeMap,
        default: &mut ElementProps,
        hover: &mut ElementProps,
        click: &mut ElementProps,
    ) {
        crate::set_missing_attrs!(
            attrs,

            "width" => default.node.width = Val::Px(250.0),
            "hover.width" => hover.node.width = default.node.width,
            "click.width" => click.node.width = default.node.width,

            "height" => default.node.height = Val::Px(250.0),
            "hover.height" => hover.node.height = default.node.height,
            "click.height" => click.node.height = default.node.height,

            "flex-grow" => default.node.flex_grow = 1.0,
            "hover.flex-grow" => hover.node.flex_grow = default.node.flex_grow,
            "click.flex-grow" => click.node.flex_grow = default.node.flex_grow,
        );
    }

    fn dyn_clone(&self) -> Box<dyn Widget> {
        Box::new(self.clone())
    }
}

/// The properties of an [ImageWidget].
#[derive(Clone, Debug)]
pub struct ImageProps {
    /// The source of the image.
    ///
    /// When the `src` attribute is set, this will equal `ImageSource::Path(src)`.
    pub src: ImageSource,
    /// The color/tint of the image.
    pub color: Color,
    /// The flip-x attribute.
    pub flip_x: bool,
    /// The flip-y attribute.
    pub flip_y: bool,
    /// The optional rect to use for the image.
    pub rect: Option<Rect>,
    /// The mode to use for the image.
    pub mode: NodeImageMode,
    /// The visual box to use for the image.
    pub visual_box: VisualBox,
    /// The [BorderRect] to use for the image when in `mode = "sliced"`.
    ///
    /// Unused when `mode` is not `"sliced"`.
    pub sliced_border: BorderRect,
    /// The center stretch value to use for the image when `mode = "sliced"` and `sliced-center-scale = "tile"`.
    ///
    /// Unused when `mode` is not `"sliced"` and `sliced-center-scale` is not `"tile"`.
    pub sliced_center_scale_stretch: f32,
    /// The center [SliceScaleMode] to use for the image when `mode = "sliced"`.
    ///
    /// Unused when `mode` is not `"sliced"`.
    pub sliced_center_scale: SliceScaleMode,
    /// The sides stretch value to use for the image when `mode = "sliced"` and `sliced-sides-scale = "tile"`.
    ///
    /// Unused when `mode` is not `"sliced"` and `sliced-sides-scale` is not `"tile"`.
    pub sliced_sides_scale_stretch: f32,
    /// The sides [SliceScaleMode] to use for the image when `mode = "sliced"`.
    ///
    /// Unused when `mode` is not `"sliced"`.
    pub sliced_sides_scale: SliceScaleMode,
    /// The max corner scale to use for the image when `mode = "sliced"`.
    ///
    /// Unused when `mode` is not `"sliced"`.
    pub sliced_max_corner_scale: f32,
    /// If the image should repeat on the x-axis when in `mode = "tiled"`.
    ///
    /// Unused when `mode` is not `"tiled"`.
    pub tiled_x: bool,
    /// If the image should repeat on the y-axis when in `mode = "tiled"`.
    ///
    /// Unused when `mode` is not `"tiled"`.
    pub tiled_y: bool,
    /// The stretch value to use for the image when `mode = "tiled"`.
    ///
    /// Unused when `mode` is not `"tiled"`.
    pub tiled_stretch: f32,
}

impl ImageProps {
    fn parse(
        attrs: &AttributeMap,
        prefix: Option<&str>,
        base: &Self,
    ) -> bevy::prelude::Result<Self, String> {
        let src = parse_attribute(attrs, "src", prefix, |s| {
            Ok(ImageSource::Path(s.to_string()))
        })?
        .unwrap_or_else(|| base.src.clone());

        let color = parse_attribute(attrs, "color", prefix, parse_color)?.unwrap_or(base.color);

        let flip_x = parse_attribute(attrs, "flip-x", prefix, parse_bool)?.unwrap_or(base.flip_x);

        let flip_y = parse_attribute(attrs, "flip-y", prefix, parse_bool)?.unwrap_or(base.flip_y);

        let rect = parse_attribute(attrs, "rect", prefix, parse_rect)?.or(base.rect);

        let sliced_border = parse_attribute(attrs, "sliced-border", prefix, parse_border_rect)?
            .unwrap_or(base.sliced_border);

        let sliced_center_scale_stretch =
            parse_attribute(attrs, "sliced-center-scale-stretch", prefix, parse_float)?
                .unwrap_or(base.sliced_center_scale_stretch);

        let sliced_center_scale = parse_attribute(attrs, "sliced-center-scale", prefix, |s| {
            parse_matches(
                s,
                &[
                    ("stretch", &|| Ok(SliceScaleMode::Stretch)),
                    ("tile", &|| {
                        Ok(SliceScaleMode::Tile {
                            stretch_value: sliced_center_scale_stretch,
                        })
                    }),
                ],
            )
        })?
        .unwrap_or(base.sliced_center_scale);

        let sliced_sides_scale_stretch =
            parse_attribute(attrs, "sliced-sides-scale-stretch", prefix, parse_float)?
                .unwrap_or(base.sliced_sides_scale_stretch);

        let sliced_sides_scale = parse_attribute(attrs, "sliced-sides-scale", prefix, |s| {
            parse_matches(
                s,
                &[
                    ("stretch", &|| Ok(SliceScaleMode::Stretch)),
                    ("tile", &|| {
                        Ok(SliceScaleMode::Tile {
                            stretch_value: sliced_sides_scale_stretch,
                        })
                    }),
                ],
            )
        })?
        .unwrap_or(base.sliced_sides_scale);

        let sliced_max_corner_scale =
            parse_attribute(attrs, "sliced-max-corner-scale", prefix, parse_float)?
                .unwrap_or(base.sliced_max_corner_scale);

        let tiled_x =
            parse_attribute(attrs, "tiled-x", prefix, parse_bool)?.unwrap_or(base.tiled_x);

        let tiled_y =
            parse_attribute(attrs, "tiled-y", prefix, parse_bool)?.unwrap_or(base.tiled_y);

        let tiled_stretch = parse_attribute(attrs, "tiled-stretch", prefix, parse_float)?
            .unwrap_or(base.tiled_stretch);

        let mode = parse_attribute(attrs, "mode", prefix, |s| {
            parse_matches(
                s,
                &[
                    ("auto", &|| Ok(NodeImageMode::Auto)),
                    ("sliced", &|| {
                        Ok(NodeImageMode::Sliced(TextureSlicer::default()))
                    }),
                    ("tiled", &|| {
                        Ok(NodeImageMode::Tiled {
                            tile_x: tiled_x,
                            tile_y: tiled_y,
                            stretch_value: tiled_stretch,
                        })
                    }),
                    ("stretch", &|| Ok(NodeImageMode::Stretch)),
                ],
            )
        })?
        .unwrap_or_else(|| base.mode.clone());

        let visual_box = parse_attribute(attrs, "visual-box", prefix, |s| {
            parse_matches(
                s,
                &[
                    ("padding", &|| Ok(VisualBox::PaddingBox)),
                    ("content", &|| Ok(VisualBox::ContentBox)),
                    ("border", &|| Ok(VisualBox::BorderBox)),
                ],
            )
        })?
        .unwrap_or(base.visual_box);

        let mut props = Self {
            src,
            color,
            flip_x,
            flip_y,
            rect,
            mode,
            visual_box,
            sliced_border,
            sliced_center_scale_stretch,
            sliced_center_scale,
            sliced_sides_scale_stretch,
            sliced_sides_scale,
            sliced_max_corner_scale,
            tiled_x,
            tiled_y,
            tiled_stretch,
        };

        props.mode = props.compute_mode();

        Ok(props)
    }

    /// Constructs the final [NodeImageMode] dynamically from all individual slice and tile attributes.
    pub fn compute_mode(&self) -> NodeImageMode {
        match &self.mode {
            NodeImageMode::Auto => NodeImageMode::Auto,
            NodeImageMode::Stretch => NodeImageMode::Stretch,
            NodeImageMode::Sliced(_) => {
                let center_scale_mode = match self.sliced_center_scale {
                    SliceScaleMode::Stretch => SliceScaleMode::Stretch,
                    SliceScaleMode::Tile { .. } => SliceScaleMode::Tile {
                        stretch_value: self.sliced_center_scale_stretch,
                    },
                };

                let sides_scale_mode = match self.sliced_sides_scale {
                    SliceScaleMode::Stretch => SliceScaleMode::Stretch,
                    SliceScaleMode::Tile { .. } => SliceScaleMode::Tile {
                        stretch_value: self.sliced_sides_scale_stretch,
                    },
                };

                NodeImageMode::Sliced(TextureSlicer {
                    border: self.sliced_border,
                    center_scale_mode,
                    sides_scale_mode,
                    max_corner_scale: self.sliced_max_corner_scale,
                })
            }
            NodeImageMode::Tiled { .. } => NodeImageMode::Tiled {
                tile_x: self.tiled_x,
                tile_y: self.tiled_y,
                stretch_value: self.tiled_stretch,
            },
        }
    }
}

impl Default for ImageProps {
    #[inline(always)]
    fn default() -> Self {
        Self {
            src: ImageSource::Path("".to_string()),
            color: Color::WHITE,
            flip_x: false,
            flip_y: false,
            rect: None,
            mode: NodeImageMode::default(),
            visual_box: VisualBox::default(),
            sliced_border: BorderRect::default(),
            sliced_center_scale_stretch: 1.0,
            sliced_center_scale: SliceScaleMode::default(),
            sliced_sides_scale_stretch: 1.0,
            sliced_sides_scale: SliceScaleMode::default(),
            sliced_max_corner_scale: 1.0,
            tiled_x: true,
            tiled_y: true,
            tiled_stretch: 1.0,
        }
    }
}