1use crate::catalog::{LbcatSource, LensCatalogSource, ZmxFileSource};
14use crate::error::Result;
15use crate::plugin::Registry;
16use crate::usercoating::{CoatingCatalog, CoatingSet, CoatingSource};
17use crate::usermaterial::{MaterialCatalog, MaterialModel};
18use crate::usershape::ShapeModel;
19use crate::usersource::SourceModel;
20use crate::usersurf::{IdealMapping, SurfaceModel};
21use crate::{invalid, RwLockExt};
22use std::any::{Any, TypeId};
23use std::collections::BTreeMap;
24use std::sync::{Arc, RwLock};
25
26pub type CatalogSource = Arc<dyn LensCatalogSource + Send + Sync>;
28
29#[derive(Clone)]
32pub struct Ext {
33 sources: Vec<CatalogSource>,
35 surfaces: BTreeMap<String, Arc<dyn SurfaceModel>>,
36 shapes: BTreeMap<String, Arc<dyn ShapeModel>>,
37 sources_m: BTreeMap<String, Arc<dyn SourceModel>>,
39 materials: BTreeMap<String, Arc<MaterialCatalog>>,
41 coat_sources: Vec<Arc<dyn CoatingSource>>,
43 coatings: BTreeMap<String, Arc<CoatingCatalog>>,
45 plugins: Registry,
46 slots: BTreeMap<TypeId, Arc<dyn Any + Send + Sync>>,
48}
49
50impl Default for Ext {
51 fn default() -> Self {
52 let mut surfaces: BTreeMap<String, Arc<dyn SurfaceModel>> = BTreeMap::new();
53 surfaces.insert("ideal_mapping".into(), Arc::new(IdealMapping));
54 Ext {
55 sources: Vec::new(),
56 surfaces,
57 shapes: BTreeMap::new(),
58 sources_m: BTreeMap::new(),
59 materials: BTreeMap::new(),
60 coat_sources: Vec::new(),
61 coatings: BTreeMap::new(),
62 plugins: Registry::new(),
63 slots: BTreeMap::new(),
64 }
65 }
66}
67
68impl std::fmt::Debug for Ext {
69 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70 f.debug_struct("Ext")
71 .field("sources", &self.sources.len())
72 .field("surfaces", &self.surfaces.keys().collect::<Vec<_>>())
73 .field("shapes", &self.shapes.keys().collect::<Vec<_>>())
74 .field("source_models", &self.sources_m.keys().collect::<Vec<_>>())
75 .field("materials", &self.materials.keys().collect::<Vec<_>>())
76 .field("coat_sources", &self.coat_sources.len())
77 .field("coatings", &self.coatings.keys().collect::<Vec<_>>())
78 .field("plugins", &self.plugins.list())
79 .field("slots", &self.slots.len())
80 .finish()
81 }
82}
83
84impl Ext {
85 pub fn new() -> Self {
86 Self::default()
87 }
88
89 pub fn add_catalog_source(&mut self, s: CatalogSource) -> &mut Self {
91 self.sources.push(s);
92 self
93 }
94
95 pub fn add_surface_model(&mut self, m: Arc<dyn SurfaceModel>) -> &mut Self {
97 self.surfaces.insert(m.name().to_string(), m);
98 self
99 }
100
101 pub fn remove_surface_model(&mut self, name: &str) -> bool {
103 self.surfaces.remove(name).is_some()
104 }
105
106 pub fn add_shape_model(&mut self, m: Arc<dyn ShapeModel>) -> &mut Self {
108 crate::usershape::declare(m.as_ref());
109 self.shapes.insert(m.name().to_string(), m);
110 self
111 }
112
113 pub fn remove_shape_model(&mut self, name: &str) -> bool {
115 self.shapes.remove(name).is_some()
116 }
117
118 pub fn add_source_model(&mut self, m: Arc<dyn SourceModel>) -> &mut Self {
120 self.sources_m.insert(m.name().to_string(), m);
121 self
122 }
123
124 pub fn remove_source_model(&mut self, name: &str) -> bool {
126 self.sources_m.remove(name).is_some()
127 }
128
129 pub fn add_material_catalog(
131 &mut self,
132 name: &str,
133 models: Vec<Arc<dyn MaterialModel>>,
134 ) -> &mut Self {
135 self.materials.retain(|k, _| !k.eq_ignore_ascii_case(name));
136 self.materials.insert(
137 name.to_string(),
138 Arc::new(MaterialCatalog::new(name, models)),
139 );
140 self
141 }
142
143 pub fn remove_material_catalog(&mut self, name: &str) -> bool {
145 let n = self.materials.len();
146 self.materials.retain(|k, _| !k.eq_ignore_ascii_case(name));
147 self.materials.len() != n
148 }
149
150 pub fn material_catalog(&self, name: &str) -> Option<&Arc<MaterialCatalog>> {
152 self.materials
154 .iter()
155 .find(|(k, _)| k.eq_ignore_ascii_case(name))
156 .map(|(_, c)| c)
157 }
158
159 pub fn material_catalogs(&self) -> Vec<String> {
161 self.materials.values().map(|c| c.name.clone()).collect()
162 }
163
164 pub fn add_coating_source(&mut self, s: Arc<dyn CoatingSource>) -> &mut Self {
166 self.coat_sources.push(s);
167 self
168 }
169
170 pub fn coating_sources(&self) -> Vec<Arc<dyn CoatingSource>> {
172 self.coat_sources.iter().rev().cloned().collect()
173 }
174
175 pub fn coating_source_for(&self, ext: &str) -> Option<&Arc<dyn CoatingSource>> {
177 self.coat_sources
178 .iter()
179 .rev()
180 .find(|s| s.extensions().iter().any(|e| e.eq_ignore_ascii_case(ext)))
181 }
182
183 pub fn add_coating_catalog(&mut self, name: &str, set: CoatingSet) -> &mut Self {
185 self.coatings.retain(|k, _| !k.eq_ignore_ascii_case(name));
186 self.coatings
187 .insert(name.to_string(), Arc::new(CoatingCatalog::new(name, set)));
188 self
189 }
190
191 pub fn remove_coating_catalog(&mut self, name: &str) -> bool {
193 let n = self.coatings.len();
194 self.coatings.retain(|k, _| !k.eq_ignore_ascii_case(name));
195 self.coatings.len() != n
196 }
197
198 pub fn coating_catalog(&self, name: &str) -> Option<&Arc<CoatingCatalog>> {
200 self.coatings
201 .iter()
202 .find(|(k, _)| k.eq_ignore_ascii_case(name))
203 .map(|(_, c)| c)
204 }
205
206 pub fn coating_catalogs(&self) -> Vec<String> {
208 self.coatings.values().map(|c| c.name.clone()).collect()
209 }
210
211 pub fn coating_names(&self) -> Vec<String> {
213 let mut v: Vec<String> = self
214 .coatings
215 .values()
216 .flat_map(|c| c.set().names())
217 .collect();
218 v.sort();
219 v.dedup();
220 v
221 }
222
223 pub fn find_coating(&self, coat: &str) -> Option<&Arc<CoatingCatalog>> {
225 self.coatings.values().find(|c| c.set().contains(coat))
226 }
227
228 pub fn plugins(&self) -> &Registry {
230 &self.plugins
231 }
232
233 pub fn plugins_mut(&mut self) -> &mut Registry {
235 &mut self.plugins
236 }
237
238 pub fn slot<T: Any + Send + Sync>(&self) -> Option<&T> {
240 self.slots
241 .get(&TypeId::of::<T>())
242 .and_then(|a| a.downcast_ref::<T>())
243 }
244
245 pub fn slot_mut<T: Any + Send + Sync + Clone + Default>(&mut self) -> &mut T {
247 let id = TypeId::of::<T>();
248 let a = self
249 .slots
250 .entry(id)
251 .or_insert_with(|| Arc::new(T::default()));
252 if Arc::get_mut(a).is_none() {
253 let copy = a.downcast_ref::<T>().cloned().unwrap_or_default();
254 *a = Arc::new(copy);
255 }
256 Arc::get_mut(a)
257 .and_then(|x| x.downcast_mut::<T>())
258 .expect("the slot was just made unique and of type T")
259 }
260
261 pub fn merge(&mut self, other: &Ext) -> &mut Self {
264 self.sources.extend(other.sources.iter().cloned());
265 for (k, m) in &other.surfaces {
266 self.surfaces.insert(k.clone(), m.clone());
267 }
268 for (k, m) in &other.shapes {
269 self.shapes.insert(k.clone(), m.clone());
270 }
271 for (k, m) in &other.sources_m {
272 self.sources_m.insert(k.clone(), m.clone());
273 }
274 for (k, c) in &other.materials {
275 self.materials.retain(|x, _| !x.eq_ignore_ascii_case(k));
276 self.materials.insert(k.clone(), c.clone());
277 }
278 self.coat_sources.extend(other.coat_sources.iter().cloned());
279 for (k, c) in &other.coatings {
280 self.coatings.retain(|x, _| !x.eq_ignore_ascii_case(k));
281 self.coatings.insert(k.clone(), c.clone());
282 }
283 for p in other.plugins.plugins() {
284 self.plugins.register(p.clone());
285 }
286 for (k, v) in &other.slots {
287 self.slots.insert(*k, v.clone());
288 }
289 self
290 }
291
292 pub fn catalog_sources(&self) -> Vec<CatalogSource> {
294 let mut v: Vec<CatalogSource> = self.sources.iter().rev().cloned().collect();
295 v.push(Arc::new(LbcatSource));
296 v.push(Arc::new(ZmxFileSource));
297 v
298 }
299
300 pub fn surface_model(&self, name: &str) -> Result<Arc<dyn SurfaceModel>> {
302 match self.surfaces.get(name) {
303 Some(m) => Ok(m.clone()),
304 None => invalid!(
305 "no user-defined surface model {name} (registered: {})",
306 self.surface_models().join(", ")
307 ),
308 }
309 }
310
311 pub fn surface_models(&self) -> Vec<String> {
313 self.surfaces.keys().cloned().collect()
314 }
315
316 pub fn shape_model(&self, name: &str) -> Result<Arc<dyn ShapeModel>> {
318 match self.shapes.get(name) {
319 Some(m) => Ok(m.clone()),
320 None => invalid!(
321 "no user-defined shape model {name} (registered: {})",
322 self.shape_models().join(", ")
323 ),
324 }
325 }
326
327 pub fn shape_models(&self) -> Vec<String> {
329 self.shapes.keys().cloned().collect()
330 }
331
332 pub fn source_model(&self, name: &str) -> Result<Arc<dyn SourceModel>> {
334 match self.sources_m.get(name) {
335 Some(m) => Ok(m.clone()),
336 None => invalid!(
337 "no user-defined source model {name} (registered: {})",
338 self.source_models().join(", ")
339 ),
340 }
341 }
342
343 pub fn source_models(&self) -> Vec<String> {
345 self.sources_m.keys().cloned().collect()
346 }
347}
348
349static DEFAULT: RwLock<Option<Arc<Ext>>> = RwLock::new(None);
351static UPDATE: std::sync::Mutex<()> = std::sync::Mutex::new(());
353
354pub fn set_default(e: Arc<Ext>) {
356 let _u = UPDATE.lock().unwrap_or_else(|p| p.into_inner());
357 *DEFAULT.write_ok() = Some(e);
358}
359
360pub fn update_default<R>(f: impl FnOnce(&mut Ext) -> R) -> R {
364 let _u = UPDATE.lock().unwrap_or_else(|p| p.into_inner());
365 let mut e = DEFAULT.read_ok().as_deref().cloned().unwrap_or_default();
366 let r = f(&mut e);
367 *DEFAULT.write_ok() = Some(Arc::new(e));
368 r
369}
370
371pub fn default_ext() -> Arc<Ext> {
373 DEFAULT
374 .read_ok()
375 .clone()
376 .unwrap_or_else(|| Arc::new(Ext::default()))
377}
378
379pub fn current() -> Arc<Ext> {
381 crate::par::current_ext().unwrap_or_else(default_ext)
382}
383
384pub fn with<R>(e: Arc<Ext>, f: impl FnOnce() -> R) -> R {
387 crate::par::with_ext(e, f)
388}
389
390#[cfg(test)]
391mod tests {
392 use super::*;
393 use crate::catalog::CatalogLens;
394 use std::path::Path;
395
396 struct Src(&'static str);
397 impl LensCatalogSource for Src {
398 fn extensions(&self) -> &[&str] {
399 std::slice::from_ref(&self.0)
400 }
401 fn load(&self, _: &Path) -> Result<Vec<CatalogLens>> {
402 Ok(Vec::new())
403 }
404 }
405
406 fn exts(e: &Ext) -> Vec<String> {
407 e.catalog_sources()
408 .iter()
409 .map(|s| s.extensions()[0].to_string())
410 .collect()
411 }
412
413 #[test]
415 fn scoped_table_does_not_leak() {
416 let mut a = Ext::new();
417 a.add_catalog_source(Arc::new(Src("lbext-a")));
418 let a = Arc::new(a);
419 with(a.clone(), || {
420 assert_eq!(exts(¤t())[0], "lbext-a");
421 let v = crate::with_threads(Some(3), || {
422 crate::par::map(&[1, 2, 3, 4], |_| exts(¤t())[0].clone())
423 });
424 assert!(v.iter().all(|x| x == "lbext-a"), "{v:?}");
425 });
426 assert!(!exts(¤t()).contains(&"lbext-a".to_string()));
427 let mut b = Ext::new();
429 b.add_catalog_source(Arc::new(Src("x")))
430 .add_catalog_source(Arc::new(Src("y")));
431 assert_eq!(exts(&b), ["y", "x", "lbcat", "zmx"]);
432 }
433
434 #[test]
436 fn surface_models_and_merge() {
437 let e = Ext::default();
438 assert!(e.surface_model("ideal_mapping").is_ok());
439 assert!(e.surface_model("nope").is_err());
440 let mut a = Ext::new();
441 a.remove_surface_model("ideal_mapping");
442 assert!(a.surface_models().is_empty());
443 a.merge(&e);
444 assert_eq!(a.surface_models(), ["ideal_mapping"]);
445 }
446
447 #[test]
449 fn slots_are_per_type_and_copy_on_write() {
450 #[derive(Clone, Default, Debug, PartialEq)]
451 struct Names(Vec<&'static str>);
452 let mut a = Ext::new();
453 assert!(a.slot::<Names>().is_none());
454 a.slot_mut::<Names>().0.push("x");
455 let mut b = a.clone();
456 b.slot_mut::<Names>().0.push("y");
457 assert_eq!(a.slot::<Names>().unwrap().0, ["x"]);
458 assert_eq!(b.slot::<Names>().unwrap().0, ["x", "y"]);
459 assert!(a.slot::<u32>().is_none());
460 with(Arc::new(b), || {
461 assert_eq!(current().slot::<Names>().unwrap().0.len(), 2);
462 });
463 }
464
465 #[test]
466 fn update_default_can_read_the_table() {
467 let n = update_default(|_| exts(¤t()).len());
469 assert_eq!(n, exts(&default_ext()).len());
470 }
471}