ferroui-base 0.4.0

The base library of FerroUI: the property system, layout, input, styling, media, text, animation, data binding and the compositor
Documentation
// @generated by scripts/generate_composition.py — do not edit

//! `AmbientLight`.
//!
//! Defined by the FerroUI overlay (scripts/composition-schema-winui.xml).

use bitflags::bitflags;
use crate::media::Color;
use crate::rendering::composition::animations::AnimationInstanceFactory;
use crate::rendering::composition::animations::ICompositionAnimation;
use crate::rendering::composition::expressions::ExpressionVariant;
use crate::rendering::composition::server::CompositionProperty;
use crate::rendering::composition::server::CompositionPropertyOf;
use crate::rendering::composition::server::ServerPropertyValue;
use crate::rendering::composition::server::props_of;
use crate::rendering::composition::transport::BatchStreamReader;
use crate::rendering::composition::transport::BatchStreamWriter;
use crate::rendering::composition::transport::BatchValue;
use crate::rendering::composition::transport::BatchValueReader;
use std::any::Any;
use std::any::TypeId;
use std::cell::Cell;
use std::sync::OnceLock;
use std::time::Duration;
use super::CompositionLightHooks;
use super::CompositionLightProps;
use super::ServerCompositionLightHooks;
use super::ServerCompositionLightProps;

bitflags! {
    /// The fields of `AmbientLight` that changed since its last serialization.
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
    pub struct AmbientLightChangedFields: u8 {
        const COLOR = 1;
        const COLOR_ANIMATED = 2;
        const INTENSITY = 4;
        const INTENSITY_ANIMATED = 8;
    }
}

impl BatchValue for AmbientLightChangedFields {
    #[inline]
    fn write_to(&self, out: &mut Vec<u8>) {
        self.bits().write_to(out);
    }

    #[inline]
    fn read_from(input: &mut BatchValueReader<'_>) -> Self {
        AmbientLightChangedFields::from_bits_retain(u8::read_from(input))
    }
}

/// The partial methods of `AmbientLight`: implemented by the class that embeds
/// [`AmbientLightProps`]. Every hook defaults to doing nothing.
pub trait AmbientLightHooks: CompositionLightHooks {
    fn initialize_defaults_extra(&self) {}

    fn validate_color_change(&self, _old_value: Color, _new_value: Color) {}
    fn on_color_changed(&self) {}
    fn on_color_changing(&self) {}

    fn validate_intensity_change(&self, _old_value: f32, _new_value: f32) {}
    fn on_intensity_changed(&self) {}
    fn on_intensity_changing(&self) {}
}

/// The UI-thread properties of `AmbientLight`.
pub struct AmbientLightProps {
    base: CompositionLightProps,
    changed_fields_of_ambient_light: Cell<AmbientLightChangedFields>,
    color: Cell<Color>,
    intensity: Cell<f32>,
}

impl Default for AmbientLightProps {
    fn default() -> Self {
        Self::new()
    }
}

impl AmbientLightProps {
    /// Creates the properties with every field at the default of its type.
    /// The defaults of the schema are applied by
    /// [`initialize_defaults`](Self::initialize_defaults).
    pub fn new() -> Self {
        Self {
            base: CompositionLightProps::new(),
            changed_fields_of_ambient_light: Cell::new(AmbientLightChangedFields::empty()),
            color: Cell::new(Default::default()),
            intensity: Cell::new(Default::default()),
        }
    }

    /// The properties of the base class.
    pub fn base(&self) -> &CompositionLightProps {
        &self.base
    }

    /// The `InitializeDefaults` calls of the constructor chain: the base
    /// classes first, then this class.
    pub fn initialize_defaults(&self, host: &dyn AmbientLightHooks) {
        self.base.initialize_defaults(host);
        self.initialize_own_defaults(host);
    }

    /// `InitializeDefaults` of this class alone.
    pub fn initialize_own_defaults(&self, host: &dyn AmbientLightHooks) {
        AmbientLightHooks::initialize_defaults_extra(host);
        self.set_color(host, crate::media::Colors::WHITE);
        self.set_intensity(host, 1.0);
    }

    /// `Color` (animated, default `crate::media::Colors::WHITE`, FerroUI overlay).
    pub fn color(&self) -> Color {
        self.color.get()
    }

    /// Sets `Color` (animated, default `crate::media::Colors::WHITE`, FerroUI overlay).
    pub fn set_color(&self, host: &dyn AmbientLightHooks, value: Color) {
        let mut changed = false;
        let old_value = self.color.get();
        if old_value.differs(&value) {
            AmbientLightHooks::validate_color_change(host, old_value, value);
            AmbientLightHooks::on_color_changing(host);
            changed = true;
            // Update the backing value
            self.color.set(value);
            // Register object for serialization in the next batch
            self.changed_fields_of_ambient_light.set(self.changed_fields_of_ambient_light.get() | AmbientLightChangedFields::COLOR);
            host.register_for_serialization();
            // Reset previous animation if any
            host.pending_animations().remove(ServerAmbientLightProps::id_of_color_property().base());
            self.changed_fields_of_ambient_light.set(self.changed_fields_of_ambient_light.get() & !AmbientLightChangedFields::COLOR_ANIMATED);
            // Check for implicit animations
            if let Some(animation) = host.implicit_animation("Color") {
                // Animation affects only current property
                if let Some(a) = animation.as_composition_animation() {
                    self.changed_fields_of_ambient_light.set(self.changed_fields_of_ambient_light.get() | AmbientLightChangedFields::COLOR_ANIMATED);
                    host.pending_animations().set(
                        ServerAmbientLightProps::id_of_color_property().base(),
                        a.create_instance(host.server(), Some(ExpressionVariant::create(value))),
                    );
                }
                // Animation is triggered by the current field, but does not necessary affects it
                host.start_animation_group(&animation, "Color", ExpressionVariant::create(value));
            }
        }
        self.color.set(value);
        if changed {
            AmbientLightHooks::on_color_changed(host);
        }
    }

    /// `Intensity` (animated, default `1.0`, FerroUI overlay).
    pub fn intensity(&self) -> f32 {
        self.intensity.get()
    }

    /// Sets `Intensity` (animated, default `1.0`, FerroUI overlay).
    pub fn set_intensity(&self, host: &dyn AmbientLightHooks, value: f32) {
        let mut changed = false;
        let old_value = self.intensity.get();
        if old_value.differs(&value) {
            AmbientLightHooks::validate_intensity_change(host, old_value, value);
            AmbientLightHooks::on_intensity_changing(host);
            changed = true;
            // Update the backing value
            self.intensity.set(value);
            // Register object for serialization in the next batch
            self.changed_fields_of_ambient_light.set(self.changed_fields_of_ambient_light.get() | AmbientLightChangedFields::INTENSITY);
            host.register_for_serialization();
            // Reset previous animation if any
            host.pending_animations().remove(ServerAmbientLightProps::id_of_intensity_property().base());
            self.changed_fields_of_ambient_light.set(self.changed_fields_of_ambient_light.get() & !AmbientLightChangedFields::INTENSITY_ANIMATED);
            // Check for implicit animations
            if let Some(animation) = host.implicit_animation("Intensity") {
                // Animation affects only current property
                if let Some(a) = animation.as_composition_animation() {
                    self.changed_fields_of_ambient_light.set(self.changed_fields_of_ambient_light.get() | AmbientLightChangedFields::INTENSITY_ANIMATED);
                    host.pending_animations().set(
                        ServerAmbientLightProps::id_of_intensity_property().base(),
                        a.create_instance(host.server(), Some(ExpressionVariant::create(value))),
                    );
                }
                // Animation is triggered by the current field, but does not necessary affects it
                host.start_animation_group(&animation, "Intensity", ExpressionVariant::create(value));
            }
        }
        self.intensity.set(value);
        if changed {
            AmbientLightHooks::on_intensity_changed(host);
        }
    }

    /// Connects an animation with the named property. Returns `false` when
    /// neither this class nor its generated bases have an animated property
    /// of that name: the caller continues with its hand-written base.
    pub fn start_animation(
        &self,
        host: &dyn AmbientLightHooks,
        property_name: &str,
        animation: &dyn ICompositionAnimation,
        final_value: Option<ExpressionVariant>,
    ) -> bool {
        if property_name == "Color" {
            let server = animation.create_instance(host.server(), final_value);
            host.pending_animations().set(ServerAmbientLightProps::id_of_color_property().base(), server);
            self.changed_fields_of_ambient_light.set(self.changed_fields_of_ambient_light.get() | AmbientLightChangedFields::COLOR_ANIMATED);
            host.register_for_serialization();
            return true;
        }
        if property_name == "Intensity" {
            let server = animation.create_instance(host.server(), final_value);
            host.pending_animations().set(ServerAmbientLightProps::id_of_intensity_property().base(), server);
            self.changed_fields_of_ambient_light.set(self.changed_fields_of_ambient_light.get() | AmbientLightChangedFields::INTENSITY_ANIMATED);
            host.register_for_serialization();
            return true;
        }
        false
    }

    /// Writes the changes of the object: the base class first, then the
    /// changed-fields mask and the changed members of this class.
    pub fn serialize_changes_core(&self, host: &dyn AmbientLightHooks, writer: &mut BatchStreamWriter<'_>) {
        self.base.serialize_changes_core(host, writer);
        let changed = self.changed_fields_of_ambient_light.get();
        writer.write(changed);
        if changed.contains(AmbientLightChangedFields::COLOR_ANIMATED) {
            writer.write_value(host.pending_animations().get_and_remove(ServerAmbientLightProps::id_of_color_property().base()));
        } else if changed.contains(AmbientLightChangedFields::COLOR) {
            writer.write(self.color.get());
        }
        if changed.contains(AmbientLightChangedFields::INTENSITY_ANIMATED) {
            writer.write_value(host.pending_animations().get_and_remove(ServerAmbientLightProps::id_of_intensity_property().base()));
        } else if changed.contains(AmbientLightChangedFields::INTENSITY) {
            writer.write(self.intensity.get());
        }
        self.changed_fields_of_ambient_light.set(AmbientLightChangedFields::empty());
    }
}

/// The partial methods of `ServerAmbientLight`: implemented by the class that embeds
/// [`ServerAmbientLightProps`]. Every hook defaults to doing nothing.
pub trait ServerAmbientLightHooks: ServerCompositionLightHooks {
    fn deserialize_changes_extra(&self, _reader: &mut BatchStreamReader<'_>) {}
    fn on_fields_deserialized(&self, _changed: AmbientLightChangedFields) {}
}

/// The server-side properties of `ServerAmbientLight`.
pub struct ServerAmbientLightProps {
    base: ServerCompositionLightProps,
    color: Cell<Color>,
    intensity: Cell<f32>,
}

impl Default for ServerAmbientLightProps {
    fn default() -> Self {
        Self::new()
    }
}

impl ServerAmbientLightProps {
    /// Creates the properties with every field at the default of its type; the
    /// values of the UI thread arrive with the first batch.
    pub fn new() -> Self {
        Self {
            base: ServerCompositionLightProps::new(),
            color: Cell::new(Default::default()),
            intensity: Cell::new(Default::default()),
        }
    }

    /// The properties of the base class.
    pub fn base(&self) -> &ServerCompositionLightProps {
        &self.base
    }

    /// This block or the block of a base class, by type: what
    /// `IServerObject::get_props` of the embedding class returns.
    pub fn find_props(&self, type_id: TypeId) -> Option<&dyn Any> {
        if type_id == TypeId::of::<Self>() {
            return Some(self);
        }
        self.base.find_props(type_id)
    }

    /// The composition property of `Color`.
    pub fn id_of_color_property() -> &'static CompositionPropertyOf<Color> {
        static PROPERTY: OnceLock<CompositionPropertyOf<Color>> = OnceLock::new();
        PROPERTY.get_or_init(|| {
            CompositionProperty::register::<ServerAmbientLightProps, Color>(
                "Color",
                "ServerAmbientLight",
                |obj| props_of::<ServerAmbientLightProps>(obj).color.get(),
                |obj, v| props_of::<ServerAmbientLightProps>(obj).color.set(v),
                Some(|obj| ExpressionVariant::create(props_of::<ServerAmbientLightProps>(obj).color.get())),
                Some(|obj, v: ExpressionVariant| props_of::<ServerAmbientLightProps>(obj).color.set(v.cast_or_default::<Color>())),
            )
        })
    }

    /// `Color` (animated).
    pub fn color(&self) -> Color {
        self.color.get()
    }

    pub fn set_color(&self, host: &dyn ServerAmbientLightHooks, value: Color) {
        self.color.set(value);
        host.remove_animation_for_property(Self::id_of_color_property().base());
    }

    /// The composition property of `Intensity`.
    pub fn id_of_intensity_property() -> &'static CompositionPropertyOf<f32> {
        static PROPERTY: OnceLock<CompositionPropertyOf<f32>> = OnceLock::new();
        PROPERTY.get_or_init(|| {
            CompositionProperty::register::<ServerAmbientLightProps, f32>(
                "Intensity",
                "ServerAmbientLight",
                |obj| props_of::<ServerAmbientLightProps>(obj).intensity.get(),
                |obj, v| props_of::<ServerAmbientLightProps>(obj).intensity.set(v),
                Some(|obj| ExpressionVariant::create(props_of::<ServerAmbientLightProps>(obj).intensity.get())),
                Some(|obj, v: ExpressionVariant| props_of::<ServerAmbientLightProps>(obj).intensity.set(v.cast_or_default::<f32>())),
            )
        })
    }

    /// `Intensity` (animated).
    pub fn intensity(&self) -> f32 {
        self.intensity.get()
    }

    pub fn set_intensity(&self, host: &dyn ServerAmbientLightHooks, value: f32) {
        self.intensity.set(value);
        host.remove_animation_for_property(Self::id_of_intensity_property().base());
    }

    /// Reads the changes of the object: the base class first, then the
    /// changed-fields mask and the changed members of this class.
    pub fn deserialize_changes_core(
        &self,
        host: &dyn ServerAmbientLightHooks,
        reader: &mut BatchStreamReader<'_>,
        committed_at: Duration,
    ) {
        self.base.deserialize_changes_core(host, reader, committed_at);
        ServerAmbientLightHooks::deserialize_changes_extra(host, reader);
        let changed = reader.read::<AmbientLightChangedFields>();
        if changed.contains(AmbientLightChangedFields::COLOR_ANIMATED) {
            let Some(animation) = reader.read_value::<AnimationInstanceFactory>().map(AnimationInstanceFactory::create) else {
                panic!("a batch starts an animation of `Color` without an animation instance");
            };
            host.set_animated_value(
                Self::id_of_color_property().base(),
                ExpressionVariant::create(self.color.get()),
                committed_at,
                animation,
            );
        } else if changed.contains(AmbientLightChangedFields::COLOR) {
            let value = reader.read::<Color>();
            self.set_color(host, value);
        }
        if changed.contains(AmbientLightChangedFields::INTENSITY_ANIMATED) {
            let Some(animation) = reader.read_value::<AnimationInstanceFactory>().map(AnimationInstanceFactory::create) else {
                panic!("a batch starts an animation of `Intensity` without an animation instance");
            };
            host.set_animated_value(
                Self::id_of_intensity_property().base(),
                ExpressionVariant::create(self.intensity.get()),
                committed_at,
                animation,
            );
        } else if changed.contains(AmbientLightChangedFields::INTENSITY) {
            let value = reader.read::<f32>();
            self.set_intensity(host, value);
        }
        ServerAmbientLightHooks::on_fields_deserialized(host, changed);
    }

    /// The composition property with the given name, among the properties
    /// of this class and of its generated bases that have a variant form.
    pub fn get_composition_property(name: &str) -> Option<&'static CompositionProperty> {
        if name == "Color" {
            return Some(Self::id_of_color_property().base());
        }
        if name == "Intensity" {
            return Some(Self::id_of_intensity_property().base());
        }
        ServerCompositionLightProps::get_composition_property(name)
    }
}