Skip to main content

alpha2_model/diagnose/
ids.rs

1//! Where each id of a project document is written, read from the tree.
2
3use std::collections::HashMap;
4
5use alpha2_diagnose::{Node, Path};
6
7/// A kind of object a project names by id. Ids of different kinds never refer to each other.
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
9pub enum Namespace {
10    /// `sources[*]`.
11    Source,
12    /// `effect_resources[*]`.
13    EffectResource,
14    /// `compositions[*]`.
15    Composition,
16    /// `compositions[*].nodes[*]`, scoped by the composition's id.
17    Node,
18    /// `timeline.tracks[*]`.
19    Track,
20    /// `timeline.tracks[*].clips[*]`.
21    Clip,
22    /// `data[*]`.
23    DataSet,
24    /// `audio.buses[*]`.
25    Bus,
26}
27
28impl Namespace {
29    /// Every namespace, in document order.
30    pub const ALL: [Self; 8] = [
31        Self::Source,
32        Self::EffectResource,
33        Self::Composition,
34        Self::Node,
35        Self::Track,
36        Self::Clip,
37        Self::DataSet,
38        Self::Bus,
39    ];
40
41    /// What an id of this namespace names, as a sentence says it.
42    #[must_use]
43    pub const fn noun(self) -> &'static str {
44        match self {
45            Self::Source => "source",
46            Self::EffectResource => "effect resource",
47            Self::Composition => "composition",
48            Self::Node => "composition node",
49            Self::Track => "track",
50            Self::Clip => "clip",
51            Self::DataSet => "data set",
52            Self::Bus => "audio bus",
53        }
54    }
55}
56
57#[derive(Clone, Debug, PartialEq, Eq, Hash)]
58struct Key {
59    namespace: Namespace,
60    scope: String,
61    id: String,
62}
63
64/// A timeline transition: its track, its clips and where it is written.
65#[derive(Clone, Debug)]
66pub struct TransitionPlace {
67    /// The track's id.
68    pub track: String,
69    /// The clip at progress zero.
70    pub from_clip: String,
71    /// The clip at progress one.
72    pub to_clip: String,
73    /// Where the transition is written.
74    pub path: Path,
75}
76
77/// The places of every id of a project document.
78#[derive(Clone, Debug, Default)]
79pub struct IdIndex {
80    places: HashMap<Key, Vec<Path>>,
81    order: Vec<Key>,
82    transitions: Vec<TransitionPlace>,
83}
84
85impl IdIndex {
86    /// Reads the ids of `tree`, a project document whose paths start at `root`. Entries without
87    /// a text `id` are left out.
88    #[must_use]
89    pub fn build(tree: &Node, root: &Path) -> Self {
90        let mut index = Self::default();
91        index.list(tree, root, "sources", Namespace::Source, "");
92        index.list(
93            tree,
94            root,
95            "effect_resources",
96            Namespace::EffectResource,
97            "",
98        );
99        index.list(tree, root, "data", Namespace::DataSet, "");
100        for (path, composition) in items(tree, root, "compositions") {
101            let Some(id) = text_id(composition) else {
102                continue;
103            };
104            index.add(Namespace::Composition, "", id, path.clone());
105            index.list(composition, &path, "nodes", Namespace::Node, id);
106        }
107        if let Some(timeline) = tree.get("timeline") {
108            let timeline_path = root.key("timeline");
109            for (track_path, track) in items(timeline, &timeline_path, "tracks") {
110                let Some(track_id) = text_id(track) else {
111                    continue;
112                };
113                index.add(Namespace::Track, "", track_id, track_path.clone());
114                index.list(track, &track_path, "clips", Namespace::Clip, "");
115                for (path, transition) in items(track, &track_path, "transitions") {
116                    let clip = |key| transition.get(key).and_then(Node::as_str);
117                    if let (Some(from_clip), Some(to_clip)) = (clip("from_clip"), clip("to_clip")) {
118                        index.transitions.push(TransitionPlace {
119                            track: track_id.to_owned(),
120                            from_clip: from_clip.to_owned(),
121                            to_clip: to_clip.to_owned(),
122                            path,
123                        });
124                    }
125                }
126            }
127        }
128        if let Some(audio) = tree.get("audio") {
129            index.list(audio, &root.key("audio"), "buses", Namespace::Bus, "");
130        }
131        index
132    }
133
134    fn list(&mut self, parent: &Node, at: &Path, key: &str, namespace: Namespace, scope: &str) {
135        for (path, item) in items(parent, at, key) {
136            if let Some(id) = text_id(item) {
137                self.add(namespace, scope, id, path);
138            }
139        }
140    }
141
142    fn add(&mut self, namespace: Namespace, scope: &str, id: &str, path: Path) {
143        let key = Key {
144            namespace,
145            scope: scope.to_owned(),
146            id: id.to_owned(),
147        };
148        let places = self.places.entry(key.clone()).or_default();
149        if places.is_empty() {
150            self.order.push(key);
151        }
152        places.push(path);
153    }
154
155    /// Where an object of `namespace` with `id` is written, in document order; more than one
156    /// place for a repeated id. A node's id is looked up with [`node`](Self::node).
157    #[must_use]
158    pub fn paths(&self, namespace: Namespace, id: &str) -> &[Path] {
159        self.scoped(namespace, "", id)
160    }
161
162    /// Where node `node` of composition `composition` is written.
163    #[must_use]
164    pub fn node(&self, composition: &str, node: &str) -> &[Path] {
165        self.scoped(Namespace::Node, composition, node)
166    }
167
168    fn scoped(&self, namespace: Namespace, scope: &str, id: &str) -> &[Path] {
169        self.places
170            .get(&Key {
171                namespace,
172                scope: scope.to_owned(),
173                id: id.to_owned(),
174            })
175            .map_or(&[], Vec::as_slice)
176    }
177
178    /// The ids of `namespace`, each once, in document order; for nodes, those of every
179    /// composition, or of one with [`node_ids`](Self::node_ids).
180    #[must_use]
181    pub fn ids(&self, namespace: Namespace) -> Vec<&str> {
182        let mut ids: Vec<&str> = Vec::new();
183        for key in self.order.iter().filter(|key| key.namespace == namespace) {
184            if !ids.contains(&key.id.as_str()) {
185                ids.push(&key.id);
186            }
187        }
188        ids
189    }
190
191    /// The node ids of one composition, in document order.
192    #[must_use]
193    pub fn node_ids(&self, composition: &str) -> Vec<&str> {
194        self.order
195            .iter()
196            .filter(|key| key.namespace == Namespace::Node && key.scope == composition)
197            .map(|key| key.id.as_str())
198            .collect()
199    }
200
201    /// The namespaces that hold `id`, for an id written where another kind is expected.
202    #[must_use]
203    pub fn namespaces_of(&self, id: &str) -> Vec<Namespace> {
204        Namespace::ALL
205            .into_iter()
206            .filter(|&namespace| {
207                self.order
208                    .iter()
209                    .any(|key| key.namespace == namespace && key.id == id)
210            })
211            .collect()
212    }
213
214    /// The timeline transitions, in document order.
215    #[must_use]
216    pub fn transitions(&self) -> &[TransitionPlace] {
217        &self.transitions
218    }
219
220    /// Where the transition of `track` between `from_clip` and `to_clip` is written.
221    #[must_use]
222    pub fn transition(&self, track: &str, from_clip: &str, to_clip: &str) -> Option<&Path> {
223        self.transitions
224            .iter()
225            .find(|place| {
226                place.track == track && place.from_clip == from_clip && place.to_clip == to_clip
227            })
228            .map(|place| &place.path)
229    }
230}
231
232fn text_id(node: &Node) -> Option<&str> {
233    node.get("id").and_then(Node::as_str)
234}
235
236fn items<'a>(parent: &'a Node, at: &Path, key: &str) -> Vec<(Path, &'a Node)> {
237    parent
238        .get(key)
239        .and_then(Node::as_list)
240        .map(|list| {
241            list.iter()
242                .enumerate()
243                .map(|(index, item)| (at.key(key).index(index), item))
244                .collect()
245        })
246        .unwrap_or_default()
247}