alpha2-model 0.10.0

Versioned project and timeline model for alpha2.
Documentation
//! Where each id of a project document is written, read from the tree.

use std::collections::HashMap;

use alpha2_diagnose::{Node, Path};

/// A kind of object a project names by id. Ids of different kinds never refer to each other.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Namespace {
    /// `sources[*]`.
    Source,
    /// `effect_resources[*]`.
    EffectResource,
    /// `compositions[*]`.
    Composition,
    /// `compositions[*].nodes[*]`, scoped by the composition's id.
    Node,
    /// `timeline.tracks[*]`.
    Track,
    /// `timeline.tracks[*].clips[*]`.
    Clip,
    /// `data[*]`.
    DataSet,
    /// `audio.buses[*]`.
    Bus,
}

impl Namespace {
    /// Every namespace, in document order.
    pub const ALL: [Self; 8] = [
        Self::Source,
        Self::EffectResource,
        Self::Composition,
        Self::Node,
        Self::Track,
        Self::Clip,
        Self::DataSet,
        Self::Bus,
    ];

    /// What an id of this namespace names, as a sentence says it.
    #[must_use]
    pub const fn noun(self) -> &'static str {
        match self {
            Self::Source => "source",
            Self::EffectResource => "effect resource",
            Self::Composition => "composition",
            Self::Node => "composition node",
            Self::Track => "track",
            Self::Clip => "clip",
            Self::DataSet => "data set",
            Self::Bus => "audio bus",
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct Key {
    namespace: Namespace,
    scope: String,
    id: String,
}

/// A timeline transition: its track, its clips and where it is written.
#[derive(Clone, Debug)]
pub struct TransitionPlace {
    /// The track's id.
    pub track: String,
    /// The clip at progress zero.
    pub from_clip: String,
    /// The clip at progress one.
    pub to_clip: String,
    /// Where the transition is written.
    pub path: Path,
}

/// The places of every id of a project document.
#[derive(Clone, Debug, Default)]
pub struct IdIndex {
    places: HashMap<Key, Vec<Path>>,
    order: Vec<Key>,
    transitions: Vec<TransitionPlace>,
}

impl IdIndex {
    /// Reads the ids of `tree`, a project document whose paths start at `root`. Entries without
    /// a text `id` are left out.
    #[must_use]
    pub fn build(tree: &Node, root: &Path) -> Self {
        let mut index = Self::default();
        index.list(tree, root, "sources", Namespace::Source, "");
        index.list(
            tree,
            root,
            "effect_resources",
            Namespace::EffectResource,
            "",
        );
        index.list(tree, root, "data", Namespace::DataSet, "");
        for (path, composition) in items(tree, root, "compositions") {
            let Some(id) = text_id(composition) else {
                continue;
            };
            index.add(Namespace::Composition, "", id, path.clone());
            index.list(composition, &path, "nodes", Namespace::Node, id);
        }
        if let Some(timeline) = tree.get("timeline") {
            let timeline_path = root.key("timeline");
            for (track_path, track) in items(timeline, &timeline_path, "tracks") {
                let Some(track_id) = text_id(track) else {
                    continue;
                };
                index.add(Namespace::Track, "", track_id, track_path.clone());
                index.list(track, &track_path, "clips", Namespace::Clip, "");
                for (path, transition) in items(track, &track_path, "transitions") {
                    let clip = |key| transition.get(key).and_then(Node::as_str);
                    if let (Some(from_clip), Some(to_clip)) = (clip("from_clip"), clip("to_clip")) {
                        index.transitions.push(TransitionPlace {
                            track: track_id.to_owned(),
                            from_clip: from_clip.to_owned(),
                            to_clip: to_clip.to_owned(),
                            path,
                        });
                    }
                }
            }
        }
        if let Some(audio) = tree.get("audio") {
            index.list(audio, &root.key("audio"), "buses", Namespace::Bus, "");
        }
        index
    }

    fn list(&mut self, parent: &Node, at: &Path, key: &str, namespace: Namespace, scope: &str) {
        for (path, item) in items(parent, at, key) {
            if let Some(id) = text_id(item) {
                self.add(namespace, scope, id, path);
            }
        }
    }

    fn add(&mut self, namespace: Namespace, scope: &str, id: &str, path: Path) {
        let key = Key {
            namespace,
            scope: scope.to_owned(),
            id: id.to_owned(),
        };
        let places = self.places.entry(key.clone()).or_default();
        if places.is_empty() {
            self.order.push(key);
        }
        places.push(path);
    }

    /// Where an object of `namespace` with `id` is written, in document order; more than one
    /// place for a repeated id. A node's id is looked up with [`node`](Self::node).
    #[must_use]
    pub fn paths(&self, namespace: Namespace, id: &str) -> &[Path] {
        self.scoped(namespace, "", id)
    }

    /// Where node `node` of composition `composition` is written.
    #[must_use]
    pub fn node(&self, composition: &str, node: &str) -> &[Path] {
        self.scoped(Namespace::Node, composition, node)
    }

    fn scoped(&self, namespace: Namespace, scope: &str, id: &str) -> &[Path] {
        self.places
            .get(&Key {
                namespace,
                scope: scope.to_owned(),
                id: id.to_owned(),
            })
            .map_or(&[], Vec::as_slice)
    }

    /// The ids of `namespace`, each once, in document order; for nodes, those of every
    /// composition, or of one with [`node_ids`](Self::node_ids).
    #[must_use]
    pub fn ids(&self, namespace: Namespace) -> Vec<&str> {
        let mut ids: Vec<&str> = Vec::new();
        for key in self.order.iter().filter(|key| key.namespace == namespace) {
            if !ids.contains(&key.id.as_str()) {
                ids.push(&key.id);
            }
        }
        ids
    }

    /// The node ids of one composition, in document order.
    #[must_use]
    pub fn node_ids(&self, composition: &str) -> Vec<&str> {
        self.order
            .iter()
            .filter(|key| key.namespace == Namespace::Node && key.scope == composition)
            .map(|key| key.id.as_str())
            .collect()
    }

    /// The namespaces that hold `id`, for an id written where another kind is expected.
    #[must_use]
    pub fn namespaces_of(&self, id: &str) -> Vec<Namespace> {
        Namespace::ALL
            .into_iter()
            .filter(|&namespace| {
                self.order
                    .iter()
                    .any(|key| key.namespace == namespace && key.id == id)
            })
            .collect()
    }

    /// The timeline transitions, in document order.
    #[must_use]
    pub fn transitions(&self) -> &[TransitionPlace] {
        &self.transitions
    }

    /// Where the transition of `track` between `from_clip` and `to_clip` is written.
    #[must_use]
    pub fn transition(&self, track: &str, from_clip: &str, to_clip: &str) -> Option<&Path> {
        self.transitions
            .iter()
            .find(|place| {
                place.track == track && place.from_clip == from_clip && place.to_clip == to_clip
            })
            .map(|place| &place.path)
    }
}

fn text_id(node: &Node) -> Option<&str> {
    node.get("id").and_then(Node::as_str)
}

fn items<'a>(parent: &'a Node, at: &Path, key: &str) -> Vec<(Path, &'a Node)> {
    parent
        .get(key)
        .and_then(Node::as_list)
        .map(|list| {
            list.iter()
                .enumerate()
                .map(|(index, item)| (at.key(key).index(index), item))
                .collect()
        })
        .unwrap_or_default()
}