Skip to main content

lensbench_engine/
ext.rs

1//! 拡張の登録を 1 つの値にまとめる
2//!
3//! 別の exe(非公開版など)が足すもの(プラグイン・カタログの形式・利用者定義の面と光源・材料と膜のカタログ・検出器のブロック・解析・誤りの
4//! 文の訳)を [`Extensions`] に集め、入口で 1 回 [`Extensions::install`] する。足す側のクレートは `Extensions` を
5//! 返す関数を 1 つ持てばよく、入口は呼ぶ順を気にしなくてよい。GUI の見せ方(図・欄)・Python の関数は、それぞれの
6//! クレートの拡張トレイト(`lensbench_gui::ext::GuiExtensions`・`lensbench::ext::PyExtensions`)で同じ値に足す
7//! (表の欄に入れる関数 [`Extensions::with_ext`] を使う。このクレートは egui・pyo3 を知らない)。
8//!
9//! 足したものはすべて値の表 [`lensbench_core::ext::Ext`] 1 つになる([`Extensions::ext`]。検出器の種類・解析は
10//! 表の欄。計算ごとに `lensbench_core::ext::with` で渡せる)。install はそれをプロセスの既定に重ねる。
11//!
12//! 拡張には名前([`Extensions::named`])を付けられる。名前は 2 つの拡張が同じ名前のものを足したときの誤りの文に
13//! だけ使い、利用者に見える名前(サブコマンド・検出器の type・プラグインの名前)には入らない
14
15use 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
28/// 表に足す関数([`Extensions::with_ext`])
29type Hook = Arc<dyn Fn(&mut Ext) + Send + Sync>;
30
31/// 足す拡張の集まり([`Extensions::install`] でプロセスに入れる)
32#[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    /// 名前の付いた拡張([`Extensions::merge`] の誤りの文に出る)
57    pub fn named(name: &'static str) -> Self {
58        Self {
59            name: Some(name),
60            ..Self::default()
61        }
62    }
63
64    /// 拡張の名前
65    pub fn name(&self) -> Option<&'static str> {
66        self.name
67    }
68
69    /// [`Extensions::merge`] で、前の拡張と同じ名前のものを置き換えてよい(無ければ誤り)
70    pub fn replacing(mut self) -> Self {
71        self.replacing = true;
72        self
73    }
74
75    /// プラグインを足す関数(同梱と同じ名前なら、こちらが勝つ)
76    pub fn plugins(mut self, f: fn(&mut Registry)) -> Self {
77        self.plugins.push(f);
78        self
79    }
80
81    /// レンズカタログの形式(同じ拡張子なら後から足したもの)
82    pub fn catalog_source(mut self, s: Arc<dyn LensCatalogSource + Send + Sync>) -> Self {
83        self.sources.push(s);
84        self
85    }
86
87    /// 利用者定義の面のモデル
88    pub fn surface_model(mut self, m: Arc<dyn SurfaceModel>) -> Self {
89        self.surfaces.push(m);
90        self
91    }
92
93    /// 利用者定義の形のモデル(面の種類 USERSHAPE)
94    pub fn shape_model(mut self, m: Arc<dyn ShapeModel>) -> Self {
95        self.shapes.push(m);
96        self
97    }
98
99    /// 利用者定義の光源のモデル
100    pub fn source_model(mut self, m: Arc<dyn SourceModel>) -> Self {
101        self.source_models.push(m);
102        self
103    }
104
105    /// 利用者定義の材料のカタログ(名前 name で AGF のカタログと同じに引く)
106    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    /// 膜のファイル形式(膜ファイルのフォルダの `<膜の名前>.<拡張子>` を膜の名前で読む。同じ拡張子なら後から足したもの)
116    pub fn coating_source(mut self, s: Arc<dyn CoatingSource>) -> Self {
117        self.coat_sources.push(s);
118        self
119    }
120
121    /// 膜の一覧(名前 name。中の膜は .zmx の膜ファイル・フォルダの膜より先に引く。`lensbench_core::usercoating`)
122    pub fn coating_catalog(mut self, name: &'static str, set: CoatingSet) -> Self {
123        self.coatings.push((name, set));
124        self
125    }
126
127    /// プロジェクトの検出器のブロック
128    pub fn detector(mut self, k: DetectorKind) -> Self {
129        self.detectors.push(k);
130        self
131    }
132
133    /// 解析(CLI のサブコマンド・serve の analyze・GUI の解析)
134    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    /// 表に足す関数(GUI の見せ方・Python の関数など、このクレートが型を知らない欄を足す拡張トレイトが使う)。
143    /// install・ext のときに、ほかのものを足した後で足した順に呼ぶ。install は今の表に重ねるので、同じ拡張を 2 回
144    /// install すると 2 回呼ばれる(同じものを 2 つ並べない関数にする)
145    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    /// install のときだけ呼ぶ関数(プロセスに 1 つの表に足すもの。GUI の画面の文字の訳など)。ext・merge では呼ばない。
151    /// 何度 install しても困らない関数にする
152    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    /// 誤りの文の訳の表(`lensbench_core::i18n::add_table` と同じ形の TSV)。install のときに足す
158    pub fn messages(mut self, table: &'static str) -> Self {
159        self.messages.push(table);
160        self
161    }
162
163    /// 足した誤りの文の訳の表
164    pub fn message_tables(&self) -> &[&'static str] {
165        &self.messages
166    }
167
168    /// 足した解析の名前(足した順)
169    pub fn analysis_names(&self) -> Vec<&'static str> {
170        self.analyses.iter().map(|a| a.meta().name).collect()
171    }
172
173    /// 足した検出器の種類
174    pub fn detector_kinds(&self) -> &[DetectorKind] {
175        &self.detectors
176    }
177
178    /// 足した利用者定義の面のモデル
179    pub fn surface_models(&self) -> &[Arc<dyn SurfaceModel>] {
180        &self.surfaces
181    }
182
183    /// 足した利用者定義の形のモデル
184    pub fn shape_models(&self) -> &[Arc<dyn ShapeModel>] {
185        &self.shapes
186    }
187
188    /// 足した利用者定義の光源のモデル
189    pub fn source_models(&self) -> &[Arc<dyn SourceModel>] {
190        &self.source_models
191    }
192
193    /// 足した材料のカタログ(名前とモデル)
194    pub fn material_catalogs(&self) -> &[(&'static str, Vec<Arc<dyn MaterialModel>>)] {
195        &self.materials
196    }
197
198    /// 足した膜のファイル形式
199    pub fn coating_sources(&self) -> &[Arc<dyn CoatingSource>] {
200        &self.coat_sources
201    }
202
203    /// 足した膜の一覧(名前と膜の組)
204    pub fn coating_catalogs(&self) -> &[(&'static str, CoatingSet)] {
205        &self.coatings
206    }
207
208    /// other の分を後ろに足す。2 つが同じ名前のもの(解析・検出器・プラグイン・面と形と光源のモデル・材料のカタログ・膜の一覧と膜・カタログと膜の拡張子)を
209    /// 足していれば誤り(other が [`Extensions::replacing`] なら other の方が勝つ)
210    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    /// 足すものの名前(種類を頭に付ける)
237    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    /// 足したものの表(同梱の分の上に足したもの)。名前が組み込みと重なれば誤り
303    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    /// 表 e に足す(同じ名前は置き換える)。名前が組み込みと重なれば誤り
310    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            // 同梱のガラスのカタログと同じ名前は、同梱のものを黙って隠すので誤り
325            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        // 膜の名前に一覧の名前は付かないので、2 つの一覧に同じ名前の膜があると、どちらを引くかが一覧の名前の順で黙って決まる
336        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    /// プロセスの既定に入れる(何度呼んでもよい。同じ名前は置き換える)。名前が組み込みと重なれば誤り(何も入れない)。
365    /// 誤りの文の訳も足す(同じ表は 1 回だけ)
366    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
381/// 誤りの文の訳の表を足す(同じ表は 1 回だけ)
382fn 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    /// merge した 2 つの分がどちらも入り、組み込みと同じ名前の検出器は誤りになる
412    #[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        // 表を値で渡せば、その計算だけに効く(プロセスの既定に漏れない)
434        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    /// 2 つの拡張が同じ名前のものを足すと merge が誤り(replacing なら後の方が勝つ)。表に足す関数も merge で残る
445    #[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}