gled-model 2.30.0

The data model of gled: projects, scenes, effects, animations, curves and assets
Documentation
pub mod animation;
pub mod curve;
pub mod group;
pub mod midi_controller;
pub mod output_device;
pub mod palette;
pub mod project;
pub mod scene;
pub mod svg;

use crate::asset_id::AssetId;
use crate::collection::Collections;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::{fmt::Debug, io::Read, sync::Arc};

pub trait AssetTrait:
    Serialize + DeserializeOwned + Debug + Default + Send + Sync + Clone + 'static + PartialEq
{
    const DIR_NAME: &'static str;
    const NAME: &'static str;
    const SHOW_NAME_IF_SELECTED: bool;
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(bound = "T: DeserializeOwned + Serialize")]
struct AssetOnDisk<T: AssetTrait> {
    name: Vec<String>,
    #[serde(flatten)]
    data: T,
}

/// An asset with its id. Serialized as such for the wire; files on disk use
/// `AssetOnDisk`, which takes the id from the file name.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(bound = "T: DeserializeOwned + Serialize")]
pub struct Asset<T: AssetTrait> {
    pub id: AssetId<T>,
    pub path: Vec<String>,
    pub data: T,
}

impl<T: AssetTrait> Default for Asset<T> {
    fn default() -> Self {
        Self::new(vec![format!("New {}", T::NAME)])
    }
}

impl<T: AssetTrait> Asset<T> {
    pub fn new(path: Vec<String>) -> Self {
        Self {
            id: AssetId::<T>::new(),
            path,
            data: T::default(),
        }
    }

    /// Create a copy of an asset with a new uuid
    pub fn copy(&self) -> Self {
        Self {
            id: AssetId::<T>::new(),
            path: self.path.clone(),
            data: self.data.clone(),
        }
    }

    pub fn get(id: AssetId<T>, collections: &Collections) -> Option<Arc<Self>> {
        collections.get::<T>()?.get(&id).cloned()
    }

    pub fn get_asset_from_index(index: usize, collections: &Collections) -> Option<Arc<Self>> {
        match index {
            0 => None,
            index => Self::all(collections).get(index - 1).cloned(),
        }
    }

    pub fn all(collections: &Collections) -> Vec<Arc<Asset<T>>> {
        let Some(collections) = collections.get::<T>() else {
            return vec![];
        };

        collections.assets()
    }

    /// Reads an asset from its JSON file.
    pub fn read(reader: impl Read, id: AssetId<T>) -> Result<Arc<Self>, serde_json::Error> {
        let asset: AssetOnDisk<T> = serde_json::from_reader(reader)?;

        Ok(Arc::new(Self {
            id,
            path: asset.name,
            data: asset.data,
        }))
    }

    pub fn into_json(self) -> Result<String, serde_json::Error> {
        let asset = AssetOnDisk {
            name: self.path,
            data: self.data,
        };

        serde_json::to_string_pretty(&asset)
    }

    pub fn dir(&self) -> Vec<String> {
        self.path[..self.path.len() - 1].to_owned()
    }

    pub fn name(&self) -> &str {
        self.path
            .last()
            .map(|name| name.as_str())
            .unwrap_or("No name")
    }

    pub fn change_dir(&mut self, new_dir: &[String]) {
        let name = self.path.pop();
        self.path = new_dir.to_owned();
        if let Some(name) = name {
            self.path.push(name);
        }
    }
}