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
use std::{
    convert::TryInto,
    fmt::{self, Debug, Formatter},
    sync::Arc,
};
use anyhow::{Context, Error};
use hotg_rune_core::Value;
use hotg_rune_runtime::{Capability, ParameterError};

/// A [`Capability`] which can be created by from some source object and a
/// [`Builder`].
///
/// # Note
///
/// This exists because of the way capabilities were initially designed and
/// switching to [an improved API][issue-153] would break every Rune that has
/// been compiled (which I'm okay with because we have version numbers) as well
/// as the C++ runtime (which I'm not okay with because un-breaking it requires
/// a lot of work).
///
/// The process for setting up a capability is very similar to what you'd do
/// in an OO language.
///
/// 1. Create a new instance of the object in an incomplete state
/// 2. Go through each of the fields and set them
/// 3. Use the object to generate data
///
/// [issue-153]: https://github.com/hotg-ai/rune/issues/153
pub trait SourceBackedCapability: Send + Debug + Sized + 'static {
    type Source: Debug + Send + Sync + 'static;
    type Builder: Builder + Debug + Send + Sync + 'static;

    fn generate(&mut self, buffer: &mut [u8]) -> Result<usize, Error>;

    fn from_builder(
        builder: Self::Builder,
        source: &Self::Source,
    ) -> Result<Self, Error>;
}

/// A [`Capability`] builder.
pub trait Builder: Default + Debug {
    fn set_parameter(
        &mut self,
        key: &str,
        value: Value,
    ) -> Result<(), ParameterError>;
}

/// Get a function for creating new [`Capability`] objects which can be
/// initialized by switching between different source values based on the
/// `"source"` parameter (i.e. an image or audio clip).
pub fn new_capability_switcher<S, I>(
    sources: I,
) -> impl Fn() -> Result<Box<dyn Capability>, Error>
where
    I: IntoIterator<Item = S::Source>,
    S: SourceBackedCapability,
{
    let sources: Arc<[S::Source]> = sources.into_iter().collect();

    move || {
        anyhow::ensure!(
            sources.len() > 0,
            "No sources were provided for this capability type ({})",
            std::any::type_name::<S>(),
        );

        Ok(Box::new(LazilyInitializedCapability::<S>::Incomplete {
            builder: Default::default(),
            sources: Arc::clone(&sources),
            selected_source: 0,
        }))
    }
}

/// A [`Capability`] which may be partially initialized.
enum LazilyInitializedCapability<S: SourceBackedCapability> {
    Incomplete {
        sources: Arc<[S::Source]>,
        builder: S::Builder,
        selected_source: usize,
    },
    Initialized(S),
}

impl<S: SourceBackedCapability> LazilyInitializedCapability<S> {
    /// Get the [`SourceBackedCapability`], initializing it if necessary.
    fn initialize(&mut self) -> Result<&mut S, Error> {
        if let LazilyInitializedCapability::Incomplete {
            builder,
            selected_source,
            sources,
        } = self
        {
            let builder = std::mem::take(builder);
            let source = sources.get(*selected_source).with_context(|| {
                format!(
                    "There is no source with index {} (# sources: {})",
                    selected_source,
                    sources.len(),
                )
            })?;

            log::debug!(
                "Initializing the \"{}\" with {:?} and {:?}",
                std::any::type_name::<S>(),
                builder,
                source,
            );

            let cap = S::from_builder(builder, source)
                .context("Unable to initialize the capability")?;
            *self = LazilyInitializedCapability::Initialized(cap);
        }

        match self {
            LazilyInitializedCapability::Initialized(c) => Ok(c),
            LazilyInitializedCapability::Incomplete { .. } => {
                unreachable!("We just initialized the capability")
            },
        }
    }
}

impl<S: SourceBackedCapability> Capability for LazilyInitializedCapability<S> {
    fn generate(&mut self, buffer: &mut [u8]) -> Result<usize, Error> {
        self.initialize()?.generate(buffer)
    }

    fn set_parameter(
        &mut self,
        name: &str,
        value: Value,
    ) -> Result<(), ParameterError> {
        match self {
            LazilyInitializedCapability::Incomplete {
                selected_source, ..
            } if name == "source" => {
                *selected_source = to_usize(value).map_err(|reason| {
                    ParameterError::InvalidValue { value, reason }
                })?;
                Ok(())
            },
            LazilyInitializedCapability::Incomplete { builder, .. } => {
                builder.set_parameter(name, value)
            },
            LazilyInitializedCapability::Initialized(_) => {
                Err(ParameterError::UnsupportedParameter)
            },
        }
    }
}

fn to_usize(value: Value) -> Result<usize, Error> {
    let value: i32 = value.try_into()?;
    let value: usize = value.try_into()?;
    Ok(value)
}

impl<S: SourceBackedCapability> Debug for LazilyInitializedCapability<S> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            LazilyInitializedCapability::Incomplete {
                builder,
                selected_source,
                ..
            } => f
                .debug_struct("Initialized")
                .field("builder", builder)
                .field("selected_source", selected_source)
                .finish_non_exhaustive(),
            LazilyInitializedCapability::Initialized(cap) => {
                f.debug_tuple("Initialized").field(cap).finish()
            },
        }
    }
}