Skip to main content

bevy_ui/widget/
inline_image.rs

1use bevy_asset::asset_changed::AssetChanged;
2use bevy_asset::AsAssetId;
3use bevy_asset::Assets;
4use bevy_asset::Handle;
5use bevy_color::Color;
6use bevy_ecs::change_detection::DetectChangesMut;
7use bevy_ecs::component::Component;
8use bevy_ecs::query::Changed;
9use bevy_ecs::query::Or;
10use bevy_ecs::reflect::ReflectComponent;
11use bevy_ecs::system::Query;
12use bevy_ecs::system::Res;
13use bevy_image::Image;
14use bevy_image::TRANSPARENT_IMAGE_HANDLE;
15use bevy_math::Vec2;
16use bevy_reflect::std_traits::ReflectDefault;
17use bevy_reflect::Reflect;
18use bevy_text::InlineBox;
19
20/// An inline image
21#[derive(#[doc =
"**Required Components**: [`InlineBox`]. \n\n A component's Required Components are inserted whenever it is inserted. Note that this will also insert the required components _of_ the required components, recursively, in depth-first order."]
impl bevy_ecs::component::Component for InlineImage where
    Self: ::core::marker::Send + ::core::marker::Sync + 'static {
    const STORAGE_TYPE: bevy_ecs::component::StorageType =
        bevy_ecs::component::StorageType::Table;
    type Mutability = bevy_ecs::component::Mutable;
    fn register_required_components(_requiree:
            bevy_ecs::component::ComponentId,
        required_components:
            &mut bevy_ecs::component::RequiredComponentsRegistrator) {
        required_components.register_required::<InlineBox>(<InlineBox as
                ::core::default::Default>::default);
    }
    fn clone_behavior() -> bevy_ecs::component::ComponentCloneBehavior {
        use bevy_ecs::component::{
            DefaultCloneBehaviorBase, DefaultCloneBehaviorViaClone,
        };
        (&&&bevy_ecs::component::DefaultCloneBehaviorSpecialization::<Self>::default()).default_clone_behavior()
    }
    fn relationship_accessor()
        ->
            ::core::option::Option<bevy_ecs::relationship::ComponentRelationshipAccessor<Self>> {
        ::core::option::Option::None
    }
}Component, #[automatically_derived]
impl ::core::fmt::Debug for InlineImage {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["color", "image", "width", "height", "flip_x", "flip_y"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.color, &self.image, &self.width, &self.height,
                        &self.flip_x, &&self.flip_y];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "InlineImage",
            names, values)
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for InlineImage {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            color: ::core::clone::Clone::clone(&self.color),
            image: ::core::clone::Clone::clone(&self.image),
            width: ::core::clone::Clone::clone(&self.width),
            height: ::core::clone::Clone::clone(&self.height),
            flip_x: ::core::clone::Clone::clone(&self.flip_x),
            flip_y: ::core::clone::Clone::clone(&self.flip_y),
        }
    }
}Clone, const _: () =
    {
        impl bevy_reflect::GetTypeRegistration for InlineImage where  {
            fn get_type_registration() -> bevy_reflect::TypeRegistration {
                let mut registration =
                    bevy_reflect::TypeRegistration::of::<Self>();
                registration.insert(<bevy_reflect::ReflectFromPtr as
                            bevy_reflect::CreateTypeData<Self>>::create_type_data(()));
                registration.insert(<bevy_reflect::ReflectFromReflect as
                            bevy_reflect::CreateTypeData<Self>>::create_type_data(()));
                registration.register_type_data_with::<ReflectComponent, Self,
                    _>(());
                registration.register_type_data_with::<ReflectDefault, Self,
                    _>(());
                registration
            }
            #[inline(never)]
            fn register_type_dependencies(registry:
                    &mut bevy_reflect::TypeRegistry) {
                <Color as
                        bevy_reflect::__macro_exports::RegisterForReflection>::__register(registry);
                <Handle<Image> as
                        bevy_reflect::__macro_exports::RegisterForReflection>::__register(registry);
                <Option<f32> as
                        bevy_reflect::__macro_exports::RegisterForReflection>::__register(registry);
                <bool as
                        bevy_reflect::__macro_exports::RegisterForReflection>::__register(registry);
            }
        }
        impl bevy_reflect::Typed for InlineImage where  {
            #[inline(never)]
            fn type_info() -> &'static bevy_reflect::TypeInfo {
                static CELL: bevy_reflect::utility::NonGenericTypeInfoCell =
                    bevy_reflect::utility::NonGenericTypeInfoCell::new();
                CELL.get_or_set(#[inline(never)] ||
                        {
                            bevy_reflect::TypeInfo::Struct(bevy_reflect::structs::StructInfo::new::<Self>(&[bevy_reflect::NamedField::new::<Color>("color"),
                                                bevy_reflect::NamedField::new::<Handle<Image>>("image"),
                                                bevy_reflect::NamedField::new::<Option<f32>>("width"),
                                                bevy_reflect::NamedField::new::<Option<f32>>("height"),
                                                bevy_reflect::NamedField::new::<bool>("flip_x"),
                                                bevy_reflect::NamedField::new::<bool>("flip_y")]))
                        })
            }
        }
        #[allow(deprecated, reason =
        "derives on a deprecated type shouldn't be considered a usage")]
        impl bevy_reflect::TypePath for InlineImage where  {
            fn type_path() -> &'static str {
                "bevy_ui::widget::inline_image::InlineImage"
            }
            fn short_type_path() -> &'static str { "InlineImage" }
            fn type_ident() -> ::core::option::Option<&'static str> {
                ::core::option::Option::Some("InlineImage")
            }
            fn crate_name() -> ::core::option::Option<&'static str> {
                ::core::option::Option::Some("bevy_ui::widget::inline_image".split(':').next().unwrap())
            }
            fn module_path() -> ::core::option::Option<&'static str> {
                ::core::option::Option::Some("bevy_ui::widget::inline_image")
            }
        }
        impl bevy_reflect::Reflect for InlineImage where  {
            #[inline]
            fn into_any(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                ->
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn ::core::any::Any> {
                self
            }
            #[inline]
            fn as_any(&self) -> &dyn ::core::any::Any { self }
            #[inline]
            fn as_any_mut(&mut self) -> &mut dyn ::core::any::Any { self }
            #[inline]
            fn into_reflect(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                ->
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect> {
                self
            }
            #[inline]
            fn as_reflect(&self) -> &dyn bevy_reflect::Reflect { self }
            #[inline]
            fn as_reflect_mut(&mut self) -> &mut dyn bevy_reflect::Reflect {
                self
            }
            #[inline]
            fn set(&mut self,
                value:
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect>)
                ->
                    ::core::result::Result<(),
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect>> {
                *self = <dyn bevy_reflect::Reflect>::take(value)?;
                ::core::result::Result::Ok(())
            }
        }
        #[allow(non_upper_case_globals)]
        const _: () =
            {
                static __INVENTORY: ::inventory::Node =
                    ::inventory::Node {
                        value: &{
                                bevy_reflect::__macro_exports::auto_register::AutomaticReflectRegistrations(<InlineImage
                                        as
                                        bevy_reflect::__macro_exports::auto_register::RegisterForReflection>::__register)
                            },
                        next: ::inventory::__private::UnsafeCell::new(::inventory::__private::Option::None),
                    };
                #[link_section = ".text.startup"]
                unsafe extern "C" fn __ctor() {
                    unsafe {
                        ::inventory::ErasedNode::submit(__INVENTORY.value,
                            &__INVENTORY)
                    }
                }
                #[used]
                #[link_section = ".init_array"]
                static __CTOR: unsafe extern "C" fn() = __ctor;
            };
        impl bevy_reflect::structs::Struct for InlineImage where  {
            fn field(&self, name: &str)
                -> ::core::option::Option<&dyn bevy_reflect::PartialReflect> {
                match name {
                    "color" => ::core::option::Option::Some(&self.color),
                    "image" => ::core::option::Option::Some(&self.image),
                    "width" => ::core::option::Option::Some(&self.width),
                    "height" => ::core::option::Option::Some(&self.height),
                    "flip_x" => ::core::option::Option::Some(&self.flip_x),
                    "flip_y" => ::core::option::Option::Some(&self.flip_y),
                    _ => ::core::option::Option::None,
                }
            }
            fn field_mut(&mut self, name: &str)
                ->
                    ::core::option::Option<&mut dyn bevy_reflect::PartialReflect> {
                match name {
                    "color" => ::core::option::Option::Some(&mut self.color),
                    "image" => ::core::option::Option::Some(&mut self.image),
                    "width" => ::core::option::Option::Some(&mut self.width),
                    "height" => ::core::option::Option::Some(&mut self.height),
                    "flip_x" => ::core::option::Option::Some(&mut self.flip_x),
                    "flip_y" => ::core::option::Option::Some(&mut self.flip_y),
                    _ => ::core::option::Option::None,
                }
            }
            fn field_at(&self, index: usize)
                -> ::core::option::Option<&dyn bevy_reflect::PartialReflect> {
                match index {
                    0usize => ::core::option::Option::Some(&self.color),
                    1usize => ::core::option::Option::Some(&self.image),
                    2usize => ::core::option::Option::Some(&self.width),
                    3usize => ::core::option::Option::Some(&self.height),
                    4usize => ::core::option::Option::Some(&self.flip_x),
                    5usize => ::core::option::Option::Some(&self.flip_y),
                    _ => ::core::option::Option::None,
                }
            }
            fn field_at_mut(&mut self, index: usize)
                ->
                    ::core::option::Option<&mut dyn bevy_reflect::PartialReflect> {
                match index {
                    0usize => ::core::option::Option::Some(&mut self.color),
                    1usize => ::core::option::Option::Some(&mut self.image),
                    2usize => ::core::option::Option::Some(&mut self.width),
                    3usize => ::core::option::Option::Some(&mut self.height),
                    4usize => ::core::option::Option::Some(&mut self.flip_x),
                    5usize => ::core::option::Option::Some(&mut self.flip_y),
                    _ => ::core::option::Option::None,
                }
            }
            fn name_at(&self, index: usize) -> ::core::option::Option<&str> {
                match index {
                    0usize => ::core::option::Option::Some("color"),
                    1usize => ::core::option::Option::Some("image"),
                    2usize => ::core::option::Option::Some("width"),
                    3usize => ::core::option::Option::Some("height"),
                    4usize => ::core::option::Option::Some("flip_x"),
                    5usize => ::core::option::Option::Some("flip_y"),
                    _ => ::core::option::Option::None,
                }
            }
            fn index_of_name(&self, name: &str)
                -> ::core::option::Option<usize> {
                match name {
                    "color" => ::core::option::Option::Some(0usize),
                    "image" => ::core::option::Option::Some(1usize),
                    "width" => ::core::option::Option::Some(2usize),
                    "height" => ::core::option::Option::Some(3usize),
                    "flip_x" => ::core::option::Option::Some(4usize),
                    "flip_y" => ::core::option::Option::Some(5usize),
                    _ => ::core::option::Option::None,
                }
            }
            fn field_len(&self) -> usize { 6usize }
            fn iter_fields(&self) -> bevy_reflect::structs::FieldIter {
                bevy_reflect::structs::FieldIter::new(self)
            }
            fn to_dynamic_struct(&self)
                ->
                    ::core::result::Result<bevy_reflect::structs::DynamicStruct,
                    bevy_reflect::ReflectCloneError> {
                let mut dynamic: bevy_reflect::structs::DynamicStruct =
                    ::core::default::Default::default();
                dynamic.set_represented_type(bevy_reflect::PartialReflect::get_represented_type_info(self));
                dynamic.insert_boxed("color",
                    bevy_reflect::PartialReflect::to_dynamic(&self.color)?);
                dynamic.insert_boxed("image",
                    bevy_reflect::PartialReflect::to_dynamic(&self.image)?);
                dynamic.insert_boxed("width",
                    bevy_reflect::PartialReflect::to_dynamic(&self.width)?);
                dynamic.insert_boxed("height",
                    bevy_reflect::PartialReflect::to_dynamic(&self.height)?);
                dynamic.insert_boxed("flip_x",
                    bevy_reflect::PartialReflect::to_dynamic(&self.flip_x)?);
                dynamic.insert_boxed("flip_y",
                    bevy_reflect::PartialReflect::to_dynamic(&self.flip_y)?);
                ::core::result::Result::Ok(dynamic)
            }
        }
        impl bevy_reflect::PartialReflect for InlineImage where  {
            #[inline]
            fn get_represented_type_info(&self)
                -> ::core::option::Option<&'static bevy_reflect::TypeInfo> {
                ::core::option::Option::Some(<Self as
                            bevy_reflect::Typed>::type_info())
            }
            #[inline]
            fn try_apply(&mut self, value: &dyn bevy_reflect::PartialReflect)
                -> ::core::result::Result<(), bevy_reflect::ApplyError> {
                if let bevy_reflect::ReflectRef::Struct(struct_value) =
                        bevy_reflect::PartialReflect::reflect_ref(value) {
                    for (name, value) in
                        bevy_reflect::structs::Struct::iter_fields(struct_value) {
                        if let ::core::option::Option::Some(v) =
                                bevy_reflect::structs::Struct::field_mut(self, name) {
                            bevy_reflect::PartialReflect::try_apply(v, value)?;
                        }
                    }
                } else {
                    return ::core::result::Result::Err(bevy_reflect::ApplyError::MismatchedKinds {
                                from_kind: bevy_reflect::PartialReflect::reflect_kind(value),
                                to_kind: bevy_reflect::ReflectKind::Struct,
                            });
                }
                ::core::result::Result::Ok(())
            }
            #[inline]
            fn reflect_kind(&self) -> bevy_reflect::ReflectKind {
                bevy_reflect::ReflectKind::Struct
            }
            #[inline]
            fn reflect_ref(&self) -> bevy_reflect::ReflectRef {
                bevy_reflect::ReflectRef::Struct(self)
            }
            #[inline]
            fn reflect_mut(&mut self) -> bevy_reflect::ReflectMut {
                bevy_reflect::ReflectMut::Struct(self)
            }
            #[inline]
            fn reflect_owned(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                -> bevy_reflect::ReflectOwned {
                bevy_reflect::ReflectOwned::Struct(self)
            }
            #[inline]
            fn try_into_reflect(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                ->
                    ::core::result::Result<bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect>,
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::PartialReflect>> {
                ::core::result::Result::Ok(self)
            }
            #[inline]
            fn try_as_reflect(&self)
                -> ::core::option::Option<&dyn bevy_reflect::Reflect> {
                ::core::option::Option::Some(self)
            }
            #[inline]
            fn try_as_reflect_mut(&mut self)
                -> ::core::option::Option<&mut dyn bevy_reflect::Reflect> {
                ::core::option::Option::Some(self)
            }
            #[inline]
            fn into_partial_reflect(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                ->
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::PartialReflect> {
                self
            }
            #[inline]
            fn as_partial_reflect(&self)
                -> &dyn bevy_reflect::PartialReflect {
                self
            }
            #[inline]
            fn as_partial_reflect_mut(&mut self)
                -> &mut dyn bevy_reflect::PartialReflect {
                self
            }
            fn reflect_partial_eq(&self,
                value: &dyn bevy_reflect::PartialReflect)
                -> ::core::option::Option<bool> {
                let value =
                    <dyn bevy_reflect::PartialReflect>::try_downcast_ref::<Self>(value);
                if let ::core::option::Option::Some(value) = value {
                    ::core::option::Option::Some(::core::cmp::PartialEq::eq(self,
                            value))
                } else { ::core::option::Option::Some(false) }
            }
            fn reflect_partial_cmp(&self,
                value: &dyn bevy_reflect::PartialReflect)
                -> ::core::option::Option<::core::cmp::Ordering> {
                (bevy_reflect::structs::struct_partial_cmp)(self, value)
            }
            fn debug(&self, f: &mut ::core::fmt::Formatter<'_>)
                -> ::core::fmt::Result {
                ::core::fmt::Debug::fmt(self, f)
            }
            #[inline]
            fn reflect_clone(&self)
                ->
                    ::core::result::Result<bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect>,
                    bevy_reflect::ReflectCloneError> {
                ::core::result::Result::Ok(bevy_reflect::__macro_exports::alloc_utils::Box::new(::core::clone::Clone::clone(self)))
            }
        }
        impl bevy_reflect::FromReflect for InlineImage where  {
            fn from_reflect(reflect: &dyn bevy_reflect::PartialReflect)
                -> ::core::option::Option<Self> {
                if let bevy_reflect::ReflectRef::Struct(__ref_struct) =
                        bevy_reflect::PartialReflect::reflect_ref(reflect) {
                    let mut __this =
                        <Self as ::core::default::Default>::default();
                    if let ::core::option::Option::Some(__field) =
                            (||
                                        <Color as
                                                bevy_reflect::FromReflect>::from_reflect(bevy_reflect::structs::Struct::field(__ref_struct,
                                                    "color")?))() {
                        __this.color = __field;
                    }
                    if let ::core::option::Option::Some(__field) =
                            (||
                                        <Handle<Image> as
                                                bevy_reflect::FromReflect>::from_reflect(bevy_reflect::structs::Struct::field(__ref_struct,
                                                    "image")?))() {
                        __this.image = __field;
                    }
                    if let ::core::option::Option::Some(__field) =
                            (||
                                        <Option<f32> as
                                                bevy_reflect::FromReflect>::from_reflect(bevy_reflect::structs::Struct::field(__ref_struct,
                                                    "width")?))() {
                        __this.width = __field;
                    }
                    if let ::core::option::Option::Some(__field) =
                            (||
                                        <Option<f32> as
                                                bevy_reflect::FromReflect>::from_reflect(bevy_reflect::structs::Struct::field(__ref_struct,
                                                    "height")?))() {
                        __this.height = __field;
                    }
                    if let ::core::option::Option::Some(__field) =
                            (||
                                        <bool as
                                                bevy_reflect::FromReflect>::from_reflect(bevy_reflect::structs::Struct::field(__ref_struct,
                                                    "flip_x")?))() {
                        __this.flip_x = __field;
                    }
                    if let ::core::option::Option::Some(__field) =
                            (||
                                        <bool as
                                                bevy_reflect::FromReflect>::from_reflect(bevy_reflect::structs::Struct::field(__ref_struct,
                                                    "flip_y")?))() {
                        __this.flip_y = __field;
                    }
                    ::core::option::Option::Some(__this)
                } else { ::core::option::Option::None }
            }
        }
    };Reflect, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for InlineImage { }
#[automatically_derived]
impl ::core::cmp::PartialEq for InlineImage {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.flip_x == other.flip_x && self.flip_y == other.flip_y &&
                        self.color == other.color && self.image == other.image &&
                self.width == other.width && self.height == other.height
    }
}PartialEq)]
22#[reflect(Component, Default, Debug, PartialEq, Clone)]
23#[require(InlineBox)]
24pub struct InlineImage {
25    /// The tint color used to draw the image.
26    ///
27    /// This is multiplied by the color of each pixel in the image.
28    /// The field value defaults to solid white, which will pass the image through unmodified.
29    pub color: Color,
30    /// Handle to the texture.
31    ///
32    /// This defaults to a [`TRANSPARENT_IMAGE_HANDLE`], which points to a fully transparent 1x1 texture.
33    pub image: Handle<Image>,
34    /// Set a fixed width in logical pixels for the image's inline box target.
35    pub width: Option<f32>,
36    /// Set a fixed height in logical pixels for the image's inline box target.
37    pub height: Option<f32>,
38    /// Flip the image on the x-axis.
39    pub flip_x: bool,
40    /// Flip the image on the y-axis.
41    pub flip_y: bool,
42}
43
44impl Default for InlineImage {
45    /// A transparent 1x1 image with a solid white tint.
46    fn default() -> Self {
47        InlineImage {
48            color: Color::WHITE,
49            image: TRANSPARENT_IMAGE_HANDLE,
50            width: None,
51            height: None,
52            flip_x: false,
53            flip_y: false,
54        }
55    }
56}
57
58impl InlineImage {
59    /// Resolve the inline box size. Preserves the image's aspect ratio if dimensions unset.
60    pub fn resolve_inline_box_size(&self, image_size: Vec2) -> Vec2 {
61        match (self.width, self.height) {
62            (Some(w), Some(h)) => Vec2::new(w, h),
63            (Some(w), None) => Vec2::new(w, image_size.y * (w / image_size.x)),
64            (None, Some(h)) => Vec2::new(image_size.x * (h / image_size.y), h),
65            _ => image_size,
66        }
67    }
68}
69
70impl AsAssetId for InlineImage {
71    type Asset = Image;
72
73    fn as_asset_id(&self) -> bevy_asset::AssetId<Self::Asset> {
74        self.image.id()
75    }
76}
77
78/// For each `InlineImage` update the size of its `InlineBox` with its image size, if it changed.
79pub fn update_inline_image_boxes(
80    image_assets: Res<Assets<Image>>,
81    mut query: Query<
82        (&InlineImage, &mut InlineBox),
83        Or<(Changed<InlineImage>, AssetChanged<InlineImage>)>,
84    >,
85) {
86    for (inline_image, mut inline_box) in &mut query {
87        if let Some(size) = image_assets
88            .get(&inline_image.image)
89            .map(|image_asset| inline_image.resolve_inline_box_size(image_asset.size().as_vec2()))
90            .filter(|size| size.is_finite() && size.cmpgt(Vec2::ZERO).all())
91        {
92            inline_box.set_if_neq(InlineBox {
93                kind: bevy_text::InlineBoxKind::InFlow,
94                size,
95            });
96        } else {
97            inline_box.set_if_neq(InlineBox {
98                kind: bevy_text::InlineBoxKind::OutOfFlow,
99                size: Vec2::ZERO,
100            });
101        }
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    #[test]
110    fn resolve_inline_box_size() {
111        let image = InlineImage {
112            width: Some(20.),
113            height: Some(10.),
114            ..Default::default()
115        };
116        assert_eq!(
117            image.resolve_inline_box_size(Vec2::new(5., 10.)),
118            Vec2::new(20., 10.)
119        );
120
121        let image = InlineImage {
122            width: Some(10.),
123            height: None,
124            ..Default::default()
125        };
126        assert_eq!(
127            image.resolve_inline_box_size(Vec2::new(5., 10.)),
128            Vec2::new(10., 20.)
129        );
130
131        let image = InlineImage {
132            width: None,
133            height: Some(10.),
134            ..Default::default()
135        };
136        assert_eq!(
137            image.resolve_inline_box_size(Vec2::new(5., 10.)),
138            Vec2::new(5., 10.)
139        );
140
141        let image = InlineImage {
142            width: None,
143            height: None,
144            ..Default::default()
145        };
146        assert_eq!(
147            image.resolve_inline_box_size(Vec2::new(5., 10.)),
148            Vec2::new(5., 10.)
149        );
150    }
151}