Skip to main content

mln_engine/
registry.rs

1//! The registrations that a runtime, its renderers and its tile workers
2//! share: the expression functions, the layer types, the source types, the
3//! extension members and the routers of layers into shared targets.
4//!
5//! An app fills a [`RegistryBuilder`] by explicit calls, `mln_builtins`'s
6//! `register_builtins` first, and builds the [`Registry`] once. Tile workers
7//! in other wasm instances make the same calls, since they run the app's own
8//! module.
9
10use std::sync::Arc;
11
12use mln_style::collections::VecMap;
13use mln_style::expression::Functions;
14use mln_style::expression::functions::RegisterError;
15use mln_style::layer::{ErasedStyleLayerType, StyleLayerType};
16use mln_style::member::{ErasedMember, Member, Place};
17use mln_style::source::StyleSourceType;
18use mln_style::{Source, StyleRegistry};
19
20use crate::layer::layer_type::{ErasedLayerType, entry};
21use crate::layer::render_layer::Layer;
22use crate::layer::tile_input::input::Find;
23use crate::placement::{ErasedPlacement, Placement, participant};
24use crate::render::shared_targets::Router;
25use crate::source::erased::{self, ErasedSourceType};
26use crate::source::{SourceSummary, SourceType, kind};
27
28/// Makes a renderer's participant of a placing layer type.
29type MakePlacement = fn() -> Box<dyn ErasedPlacement>;
30
31/// What a [`Registry`] is built from.
32#[derive(Default)]
33pub struct RegistryBuilder {
34    functions: Functions,
35    layer_types: VecMap<&'static str, &'static dyn ErasedLayerType>,
36    placing_types: VecMap<&'static str, MakePlacement>,
37    source_types: VecMap<&'static str, &'static dyn ErasedSourceType>,
38    members: Vec<&'static dyn ErasedMember>,
39    routers: Vec<&'static dyn Router>,
40}
41
42impl std::fmt::Debug for RegistryBuilder {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        f.debug_struct("RegistryBuilder")
45            .field("functions", &self.functions)
46            .field("layer_types", &self.layer_types.keys().collect::<Vec<_>>())
47            .field("placing_types", &self.placing_types.keys().collect::<Vec<_>>())
48            .field("source_types", &self.source_types.keys().collect::<Vec<_>>())
49            .field("members", &self.members.iter().map(|member| member.name()).collect::<Vec<_>>())
50            .field("routers", &self.routers.len())
51            .finish()
52    }
53}
54
55impl RegistryBuilder {
56    #[must_use]
57    pub fn new() -> Self {
58        RegistryBuilder::default()
59    }
60
61    pub fn functions_mut(&mut self) -> &mut Functions {
62        &mut self.functions
63    }
64
65    /// Adds the layer type `L`, both its halves, under its style half's
66    /// name. Fails for a name that an earlier type took. A type whose input
67    /// is of another kind of source than its style half names doesn't
68    /// compile.
69    pub fn add_layer_type<L: Layer>(&mut self) -> Result<(), RegisterError> {
70        const {
71            assert!(
72                L::Style::INFO.source as u8 == <L::Input as Find<L::Style>>::KIND as u8,
73                "a layer type draws from the kind of source its style half names"
74            );
75        }
76        let name = L::Style::INFO.name;
77        if self.layer_types.contains_key(name) {
78            return Err(RegisterError::Duplicate(name.to_owned()));
79        }
80        self.layer_types.insert(name, entry::<L>());
81        Ok(())
82    }
83
84    /// Adds the layer type of `P`, a placement participant, both its
85    /// halves, whose layers place with `P` ([`Placement`]). Fails for a name
86    /// that an earlier type took.
87    pub fn add_placing_layer_type<P: Placement>(&mut self) -> Result<(), RegisterError> {
88        const { assert!(<P::Layer as Layer>::PLACES, "a placing layer type says that it places") }
89        self.add_layer_type::<P::Layer>()?;
90        self.placing_types.insert(<P::Layer as Layer>::Style::INFO.name, participant::<P>);
91        Ok(())
92    }
93
94    /// Adds the source type `T`, both its halves. Fails for a name that an
95    /// earlier type took. A type whose halves name different kinds of data
96    /// doesn't compile.
97    pub fn add_source_type<T: SourceType>(&mut self) -> Result<(), RegisterError> {
98        const {
99            assert!(
100                T::Style::INFO.layer_kind as u8 == <T::Data as kind::Deliver>::KIND as u8,
101                "a source type's halves name the same kind of data"
102            );
103        }
104        let name = T::Style::INFO.name;
105        if self.source_types.contains_key(name) {
106            return Err(RegisterError::Duplicate(name.to_owned()));
107        }
108        self.source_types.insert(name, erased::entry::<T>());
109        Ok(())
110    }
111
112    /// Adds the extension member `member`, which gives the style's members
113    /// of its place and name a type. Fails for a place and name that an
114    /// earlier member took.
115    pub fn add_member<T: Send + Sync + 'static>(&mut self, member: &'static Member<T>) -> Result<(), RegisterError> {
116        let taken = |added: &&dyn ErasedMember| added.place() == member.place() && added.name() == member.name();
117        if self.members.iter().any(taken) {
118            let place = match member.place() {
119                Place::Root => "root",
120                Place::Layer => "layer",
121            };
122            return Err(RegisterError::Duplicate(format!("{place} member {}", member.name())));
123        }
124        self.members.push(member);
125        Ok(())
126    }
127
128    /// Adds `router`, which declares the shared targets of the frames of
129    /// each version of a style and routes its layers' draws into them. The
130    /// routers route in the order they were added: of two routes of a
131    /// layer, the later stands.
132    pub fn add_router(&mut self, router: &'static dyn Router) {
133        self.routers.push(router);
134    }
135
136    #[must_use]
137    pub fn build(self) -> Arc<Registry> {
138        let RegistryBuilder { functions, layer_types, placing_types, source_types, members, routers } = self;
139        Registry::new(Arc::new(functions), layer_types, placing_types, source_types, members, routers)
140    }
141}
142
143fn style_half(layer_type: &'static dyn ErasedLayerType) -> &'static dyn ErasedStyleLayerType {
144    layer_type.style()
145}
146
147/// The expression functions, layer types, source types and extension
148/// members that a style parses against, its renderer draws and its tile
149/// workers lay out, built by a [`RegistryBuilder`]. It doesn't change once built.
150///
151/// A map and the renderer and tile workers that draw it must be given
152/// registries filled by the same calls: they identify functions, layer
153/// types and source types by name.
154pub struct Registry {
155    style: Arc<StyleRegistry>,
156    layer_types: VecMap<&'static str, &'static dyn ErasedLayerType>,
157    placing_types: VecMap<&'static str, MakePlacement>,
158    source_types: VecMap<&'static str, &'static dyn ErasedSourceType>,
159    routers: Vec<&'static dyn Router>,
160}
161
162impl std::fmt::Debug for Registry {
163    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
164        f.debug_struct("Registry").field("style", &self.style).finish_non_exhaustive()
165    }
166}
167
168impl Registry {
169    fn new(
170        functions: Arc<Functions>,
171        layer_types: VecMap<&'static str, &'static dyn ErasedLayerType>,
172        placing_types: VecMap<&'static str, MakePlacement>,
173        source_types: VecMap<&'static str, &'static dyn ErasedSourceType>,
174        members: Vec<&'static dyn ErasedMember>,
175        routers: Vec<&'static dyn Router>,
176    ) -> Arc<Registry> {
177        let style_halves = layer_types.values().map(|&layer_type| style_half(layer_type));
178        let style_source_halves = source_types.values().map(|&source_type| source_type.style());
179        let style = StyleRegistry::new(functions, style_halves, style_source_halves, members);
180        Arc::new(Registry { style: Arc::new(style), layer_types, placing_types, source_types, routers })
181    }
182
183    #[must_use]
184    pub fn style(&self) -> &Arc<StyleRegistry> {
185        &self.style
186    }
187
188    #[must_use]
189    pub fn functions(&self) -> &Arc<Functions> {
190        self.style.functions()
191    }
192
193    #[must_use]
194    pub fn layer_type(&self, name: &str) -> Option<&'static dyn ErasedLayerType> {
195        self.layer_types.get(name).copied()
196    }
197
198    /// The makers of the participants of the placing layer types, in the
199    /// order they registered.
200    pub(crate) fn placing_types(&self) -> impl Iterator<Item = MakePlacement> + '_ {
201        self.placing_types.values().copied()
202    }
203
204    /// The routers, in the order they were added.
205    pub(crate) fn routers(&self) -> &[&'static dyn Router] {
206        &self.routers
207    }
208
209    pub(crate) fn source_type(&self, name: &str) -> Option<&'static dyn ErasedSourceType> {
210        self.source_types.get(name).copied()
211    }
212
213    /// The attribution of `source`, as its type gives it: `None` for a type
214    /// the registry lacks.
215    #[must_use]
216    pub fn source_attribution(&self, source: &Source) -> Option<String> {
217        self.source_type(source.info().name)?.attribution(source)
218    }
219
220    /// What `source` reports about itself, as its type says: nothing for a
221    /// type the registry lacks.
222    #[must_use]
223    pub fn source_summary(&self, source: &Source) -> SourceSummary {
224        self.source_type(source.info().name).map(|source_type| source_type.summary(source)).unwrap_or_default()
225    }
226}
227
228/// A context in which the values that the worker codec reads resolve the
229/// registrations they name against this registry: layers' evaluated values
230/// their layer type, and as for a [`StyleRegistry`], layers' style data and
231/// compound expressions.
232impl mln_wire::Context for &Registry {
233    fn provide<'a>(&'a mut self, request: &mut mln_wire::Request<'a>) {
234        let registry: &'a Registry = self;
235        request.give(registry).give::<StyleRegistry>(registry.style()).give::<Functions>(registry.functions());
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242
243    #[test]
244    fn a_layer_type_registers_once() {
245        type Circles = crate::tests::types::layers::TestFeatures<mln_style::layers::Circle>;
246        let mut builder = RegistryBuilder::new();
247        builder.add_layer_type::<Circles>().unwrap();
248        assert_eq!(builder.add_layer_type::<Circles>(), Err(RegisterError::Duplicate("circle".to_owned())));
249    }
250}