1use lensbench_analysis::{Analyses, Analysis, DynAnalysis};
16use lensbench_core::catalog::LensCatalogSource;
17use lensbench_core::ext::Ext;
18use lensbench_core::plugin::Registry;
19use lensbench_core::usercoating::{CoatingSet, CoatingSource};
20use lensbench_core::usermaterial::MaterialModel;
21use lensbench_core::usershape::ShapeModel;
22use lensbench_core::usersource::SourceModel;
23use lensbench_core::usersurf::SurfaceModel;
24use lensbench_project::detectors::DetectorKind;
25use std::collections::BTreeSet;
26use std::sync::Arc;
27
28type Hook = Arc<dyn Fn(&mut Ext) + Send + Sync>;
30
31#[derive(Default, Clone)]
33pub struct Extensions {
34 name: Option<&'static str>,
35 replacing: bool,
36 plugins: Vec<fn(&mut Registry)>,
37 sources: Vec<Arc<dyn LensCatalogSource + Send + Sync>>,
38 surfaces: Vec<Arc<dyn SurfaceModel>>,
39 shapes: Vec<Arc<dyn ShapeModel>>,
40 source_models: Vec<Arc<dyn SourceModel>>,
41 materials: Vec<(&'static str, Vec<Arc<dyn MaterialModel>>)>,
42 coat_sources: Vec<Arc<dyn CoatingSource>>,
43 coatings: Vec<(&'static str, CoatingSet)>,
44 detectors: Vec<DetectorKind>,
45 analyses: Vec<Arc<dyn DynAnalysis>>,
46 hooks: Vec<Hook>,
47 on_install: Vec<Arc<dyn Fn() + Send + Sync>>,
48 messages: Vec<&'static str>,
49}
50
51impl Extensions {
52 pub fn new() -> Self {
53 Self::default()
54 }
55
56 pub fn named(name: &'static str) -> Self {
58 Self {
59 name: Some(name),
60 ..Self::default()
61 }
62 }
63
64 pub fn name(&self) -> Option<&'static str> {
66 self.name
67 }
68
69 pub fn replacing(mut self) -> Self {
71 self.replacing = true;
72 self
73 }
74
75 pub fn plugins(mut self, f: fn(&mut Registry)) -> Self {
77 self.plugins.push(f);
78 self
79 }
80
81 pub fn catalog_source(mut self, s: Arc<dyn LensCatalogSource + Send + Sync>) -> Self {
83 self.sources.push(s);
84 self
85 }
86
87 pub fn surface_model(mut self, m: Arc<dyn SurfaceModel>) -> Self {
89 self.surfaces.push(m);
90 self
91 }
92
93 pub fn shape_model(mut self, m: Arc<dyn ShapeModel>) -> Self {
95 self.shapes.push(m);
96 self
97 }
98
99 pub fn source_model(mut self, m: Arc<dyn SourceModel>) -> Self {
101 self.source_models.push(m);
102 self
103 }
104
105 pub fn material_catalog(
107 mut self,
108 name: &'static str,
109 models: Vec<Arc<dyn MaterialModel>>,
110 ) -> Self {
111 self.materials.push((name, models));
112 self
113 }
114
115 pub fn coating_source(mut self, s: Arc<dyn CoatingSource>) -> Self {
117 self.coat_sources.push(s);
118 self
119 }
120
121 pub fn coating_catalog(mut self, name: &'static str, set: CoatingSet) -> Self {
123 self.coatings.push((name, set));
124 self
125 }
126
127 pub fn detector(mut self, k: DetectorKind) -> Self {
129 self.detectors.push(k);
130 self
131 }
132
133 pub fn analysis<A: Analysis>(mut self, a: A) -> Self {
135 let name = a.meta().name;
136 let mut t = Analyses::default();
137 t.add(a);
138 self.analyses.extend(t.get(name).cloned());
139 self
140 }
141
142 pub fn with_ext(mut self, f: impl Fn(&mut Ext) + Send + Sync + 'static) -> Self {
146 self.hooks.push(Arc::new(f));
147 self
148 }
149
150 pub fn on_install(mut self, f: impl Fn() + Send + Sync + 'static) -> Self {
153 self.on_install.push(Arc::new(f));
154 self
155 }
156
157 pub fn messages(mut self, table: &'static str) -> Self {
159 self.messages.push(table);
160 self
161 }
162
163 pub fn message_tables(&self) -> &[&'static str] {
165 &self.messages
166 }
167
168 pub fn analysis_names(&self) -> Vec<&'static str> {
170 self.analyses.iter().map(|a| a.meta().name).collect()
171 }
172
173 pub fn detector_kinds(&self) -> &[DetectorKind] {
175 &self.detectors
176 }
177
178 pub fn surface_models(&self) -> &[Arc<dyn SurfaceModel>] {
180 &self.surfaces
181 }
182
183 pub fn shape_models(&self) -> &[Arc<dyn ShapeModel>] {
185 &self.shapes
186 }
187
188 pub fn source_models(&self) -> &[Arc<dyn SourceModel>] {
190 &self.source_models
191 }
192
193 pub fn material_catalogs(&self) -> &[(&'static str, Vec<Arc<dyn MaterialModel>>)] {
195 &self.materials
196 }
197
198 pub fn coating_sources(&self) -> &[Arc<dyn CoatingSource>] {
200 &self.coat_sources
201 }
202
203 pub fn coating_catalogs(&self) -> &[(&'static str, CoatingSet)] {
205 &self.coatings
206 }
207
208 pub fn merge(mut self, other: Extensions) -> lensbench_core::Result<Self> {
211 if !other.replacing {
212 let both: Vec<String> = self.names().intersection(&other.names()).cloned().collect();
213 if !both.is_empty() {
214 let a = self.name.unwrap_or("(unnamed)");
215 let b = other.name.unwrap_or("(unnamed)");
216 let names = both.join(", ");
217 lensbench_core::invalid!("extensions {a} and {b} both add {names}");
218 }
219 }
220 self.plugins.extend(other.plugins);
221 self.sources.extend(other.sources);
222 self.surfaces.extend(other.surfaces);
223 self.shapes.extend(other.shapes);
224 self.source_models.extend(other.source_models);
225 self.materials.extend(other.materials);
226 self.coat_sources.extend(other.coat_sources);
227 self.coatings.extend(other.coatings);
228 self.detectors.extend(other.detectors);
229 self.analyses.extend(other.analyses);
230 self.hooks.extend(other.hooks);
231 self.on_install.extend(other.on_install);
232 self.messages.extend(other.messages);
233 Ok(self)
234 }
235
236 fn names(&self) -> BTreeSet<String> {
238 let mut reg = Registry::default();
239 for f in &self.plugins {
240 f(&mut reg);
241 }
242 let mut n: BTreeSet<String> = reg
243 .list()
244 .into_iter()
245 .map(|(k, _)| format!("plugin {k}"))
246 .collect();
247 n.extend(
248 self.analysis_names()
249 .iter()
250 .map(|a| format!("analysis {a}")),
251 );
252 n.extend(
253 self.detectors
254 .iter()
255 .map(|d| format!("detector {}", d.name)),
256 );
257 n.extend(
258 self.surfaces
259 .iter()
260 .map(|m| format!("surface model {}", m.name())),
261 );
262 n.extend(
263 self.shapes
264 .iter()
265 .map(|m| format!("shape model {}", m.name())),
266 );
267 n.extend(
268 self.source_models
269 .iter()
270 .map(|m| format!("source model {}", m.name())),
271 );
272 n.extend(
273 self.materials
274 .iter()
275 .map(|(c, _)| format!("material catalog {}", c.to_ascii_uppercase())),
276 );
277 for s in &self.sources {
278 n.extend(
279 s.extensions()
280 .iter()
281 .map(|e| format!("catalog format .{e}")),
282 );
283 }
284 for (c, set) in &self.coatings {
285 n.insert(format!("coating catalog {}", c.to_ascii_uppercase()));
286 n.extend(
287 set.names()
288 .iter()
289 .map(|m| format!("coating {}", m.to_ascii_uppercase())),
290 );
291 }
292 for s in &self.coat_sources {
293 n.extend(
294 s.extensions()
295 .iter()
296 .map(|e| format!("coating format .{}", e.to_ascii_lowercase())),
297 );
298 }
299 n
300 }
301
302 pub fn ext(&self) -> lensbench_core::Result<Ext> {
304 let mut e = Ext::default();
305 self.add_to(&mut e)?;
306 Ok(e)
307 }
308
309 pub fn add_to(&self, e: &mut Ext) -> lensbench_core::Result<()> {
311 for s in &self.sources {
312 e.add_catalog_source(s.clone());
313 }
314 for m in &self.surfaces {
315 e.add_surface_model(m.clone());
316 }
317 for m in &self.shapes {
318 e.add_shape_model(m.clone());
319 }
320 for m in &self.source_models {
321 e.add_source_model(m.clone());
322 }
323 for (c, ms) in &self.materials {
324 if lensbench_core::glass::builtin::catalogs().any(|b| b.eq_ignore_ascii_case(c)) {
326 lensbench_core::invalid!(
327 "material catalog {c} has the name of a built-in glass catalog; give it another name"
328 );
329 }
330 e.add_material_catalog(c, ms.clone());
331 }
332 for s in &self.coat_sources {
333 e.add_coating_source(s.clone());
334 }
335 let mut seen: std::collections::BTreeMap<String, &str> = Default::default();
337 for (c, set) in &self.coatings {
338 for m in set.names() {
339 if let Some(o) = seen.insert(m.to_ascii_uppercase(), c) {
340 if !o.eq_ignore_ascii_case(c) {
341 lensbench_core::invalid!(
342 "coating {m} is in both coating catalogs {o} and {c}; give one of them another name"
343 );
344 }
345 }
346 }
347 e.add_coating_catalog(c, set.clone());
348 }
349 for f in &self.plugins {
350 f(e.plugins_mut());
351 }
352 for k in &self.detectors {
353 lensbench_project::detectors::add(e, *k)?;
354 }
355 for a in &self.analyses {
356 crate::registry::add_dyn(e, a.clone())?;
357 }
358 for h in &self.hooks {
359 h(e);
360 }
361 Ok(())
362 }
363
364 pub fn install(self) -> lensbench_core::Result<()> {
367 lensbench_core::ext::update_default(|e| {
368 let mut n = e.clone();
369 self.add_to(&mut n)?;
370 *e = n;
371 Ok::<(), lensbench_core::Error>(())
372 })?;
373 add_messages(&self.messages);
374 for f in &self.on_install {
375 f();
376 }
377 Ok(())
378 }
379}
380
381fn add_messages(tables: &[&'static str]) {
383 use lensbench_core::LockExt;
384 static ADDED: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
385 let mut added = ADDED.lock_ok();
386 for t in tables {
387 let key = t.as_ptr() as usize;
388 if !added.contains(&key) {
389 added.push(key);
390 lensbench_core::i18n::add_table(t);
391 }
392 }
393}
394
395#[cfg(test)]
396mod tests {
397 use super::*;
398 use lensbench_core::catalog::CatalogLens;
399 use std::path::Path;
400
401 struct Dummy;
402 impl LensCatalogSource for Dummy {
403 fn extensions(&self) -> &[&str] {
404 &["lbext-test"]
405 }
406 fn load(&self, _: &Path) -> lensbench_core::Result<Vec<CatalogLens>> {
407 Ok(Vec::new())
408 }
409 }
410
411 #[test]
413 fn install_merged_and_rejects_builtin_names() {
414 let k = |name: &'static str| DetectorKind {
415 name,
416 doc: "",
417 check: |_| Ok(()),
418 schema: None,
419 };
420 let a = Extensions::new().catalog_source(Arc::new(Dummy));
421 let b = Extensions::new().detector(k("ext-test-detector"));
422 a.merge(b).unwrap().install().unwrap();
423 let has = |e: &str| {
424 lensbench_core::ext::current()
425 .catalog_sources()
426 .iter()
427 .any(|s| s.extensions() == [e])
428 };
429 assert!(has("lbext-test"));
430 assert!(lensbench_project::detectors::get("ext-test-detector").is_some());
431 let bad = lensbench_project::BUILTIN_BLOCKS[0];
432 assert!(Extensions::new().detector(k(bad)).install().is_err());
433 let e = Extensions::new()
435 .detector(k("ext-test-scoped"))
436 .ext()
437 .unwrap();
438 lensbench_core::ext::with(Arc::new(e), || {
439 assert!(lensbench_project::detectors::get("ext-test-scoped").is_some());
440 });
441 assert!(lensbench_project::detectors::get("ext-test-scoped").is_none());
442 }
443
444 #[test]
446 fn merge_rejects_the_same_name_from_two_extensions() {
447 let k = DetectorKind {
448 name: "ext-test-twice",
449 doc: "",
450 check: |_| Ok(()),
451 schema: None,
452 };
453 let a = Extensions::named("a").detector(k);
454 let b = Extensions::named("b").detector(k);
455 let e = a
456 .clone()
457 .merge(b)
458 .err()
459 .map(|e| e.to_string())
460 .unwrap_or_default();
461 assert!(
462 e.contains("extensions a and b both add detector ext-test-twice"),
463 "{e}"
464 );
465 let b = Extensions::named("b").detector(k).replacing();
466 assert!(a.clone().merge(b).is_ok());
467
468 #[derive(Clone, Default)]
469 struct Mark(u32);
470 let c = Extensions::named("c").with_ext(|e| e.slot_mut::<Mark>().0 += 1);
471 let t = a.merge(c).unwrap().ext().unwrap();
472 assert_eq!(t.slot::<Mark>().map(|m| m.0), Some(1));
473 }
474}