Skip to main content

lensbench_core/
catalog.rs

1//! レンズカタログの差し込み口。
2//!
3//! CLI・GUI・Python が読む形式は拡張の表([`crate::ext::Ext::add_catalog_source`])で足せる(既定は .zmx と
4//! .lbcat)。別の exe に組み込むときは、起動の最初に表を決めてから CLI・GUI の入口を呼ぶ。
5//!
6//! .lbcat は lensbench のレンズカタログの束([`encode_lbcat`]): メーカーのカタログ(ZMF など)を取り込みのときに
7//! 1 回だけ変換したもの。実行時は解読せず、展開して読むだけ。
8
9use crate::error::{Error, Result};
10use std::path::Path;
11
12/// カタログ中の 1 レンズ(面データは .zmx 断片のまま持つ)。
13#[derive(Debug, Clone)]
14pub struct CatalogLens {
15    pub vendor: String,
16    pub part: String,
17    pub efl: f64,
18    pub zmx: String,
19}
20
21/// .lbcat の形式の版
22pub(crate) const LBCAT_VERSION: u32 = 1;
23
24/// レンズカタログの束 .lbcat のバイト列。zlib で圧縮した UTF-8 の文で、1 行目が
25/// `LBCAT <版>\t<メーカー>\t<変換元>`、続いてレンズごとに `<型番>\t<焦点距離>\t<.zmx のバイト数>` の行と .zmx の本文
26/// (そのバイト数ちょうど)。焦点距離が数でないレンズは `nan`。型番・メーカー・変換元にタブ・改行は使えない
27pub fn encode_lbcat(vendor: &str, source: &str, lenses: &[CatalogLens]) -> crate::Result<Vec<u8>> {
28    let clean = |what: &str, s: &str| {
29        if s.contains(['\t', '\n', '\r']) {
30            Err(format!("{what} {s:?} has a tab or line break"))
31        } else {
32            Ok(())
33        }
34    };
35    clean("maker", vendor)?;
36    clean("source", source)?;
37    let mut out = format!("LBCAT {LBCAT_VERSION}\t{vendor}\t{source}\n").into_bytes();
38    for l in lenses {
39        clean("part number", &l.part)?;
40        let efl = if l.efl.is_finite() {
41            format!("{:?}", l.efl)
42        } else {
43            "nan".into()
44        };
45        out.extend(format!("{}\t{efl}\t{}\n", l.part, l.zmx.len()).bytes());
46        out.extend(l.zmx.as_bytes());
47    }
48    Ok(miniz_oxide::deflate::compress_to_vec_zlib(&out, 9))
49}
50
51/// [`encode_lbcat`] のバイト列を読む。メーカーは束の値(空なら `default_vendor`)
52pub fn decode_lbcat(bytes: &[u8], default_vendor: &str) -> crate::Result<Vec<CatalogLens>> {
53    let b = miniz_oxide::inflate::decompress_to_vec_zlib(bytes)
54        .map_err(|e| format!("can't be inflated ({:?})", e.status))?;
55    let mut o = 0usize;
56    let line = |o: &mut usize| -> crate::Result<&str> {
57        let end = b[*o..]
58            .iter()
59            .position(|&c| c == b'\n')
60            .ok_or("a line is cut short")?;
61        let s = std::str::from_utf8(&b[*o..*o + end]).map_err(|_| "a line is not UTF-8")?;
62        *o += end + 1;
63        Ok(s)
64    };
65    let head: Vec<String> = line(&mut o)?.split('\t').map(str::to_string).collect();
66    let ver: u32 = head[0]
67        .strip_prefix("LBCAT ")
68        .and_then(|v| v.parse().ok())
69        .ok_or("not a lensbench lens catalog bundle")?;
70    if ver == 0 || ver > LBCAT_VERSION {
71        return Err(format!("format version {ver} can't be read (up to {LBCAT_VERSION})").into());
72    }
73    let vendor = match head.get(1) {
74        Some(v) if !v.trim().is_empty() => v.clone(),
75        _ => default_vendor.to_string(),
76    };
77    let mut out = Vec::new();
78    while o < b.len() {
79        let f: Vec<String> = line(&mut o)?.split('\t').map(str::to_string).collect();
80        let [part, efl, n] = &f[..] else {
81            return Err(
82                format!("a lens line doesn't have 3 fields (lens {})", out.len() + 1).into(),
83            );
84        };
85        let n: usize = n
86            .parse()
87            .map_err(|_| format!("{part}: .zmx byte count {n}"))?;
88        let end = o
89            .checked_add(n)
90            .filter(|&e| e <= b.len())
91            .ok_or_else(|| format!("{part}: the .zmx is cut short"))?;
92        let zmx = std::str::from_utf8(&b[o..end])
93            .map_err(|_| format!("{part}: the .zmx is not UTF-8"))?
94            .to_string();
95        o = end;
96        out.push(CatalogLens {
97            vendor: vendor.clone(),
98            part: part.clone(),
99            efl: efl.parse().unwrap_or(f64::NAN),
100            zmx,
101        });
102    }
103    Ok(out)
104}
105
106/// レンズカタログの束 .lbcat([`encode_lbcat`])。メーカーは束の値(なければファイル名)
107pub struct LbcatSource;
108
109impl LensCatalogSource for LbcatSource {
110    fn extensions(&self) -> &[&str] {
111        &["lbcat"]
112    }
113    fn load(&self, path: &Path) -> Result<Vec<CatalogLens>> {
114        let bytes = crate::vfs::read(path).map_err(|e| io_err(path, e))?;
115        let stem = path
116            .file_stem()
117            .map(|s| s.to_string_lossy().into_owned())
118            .unwrap_or_default();
119        decode_lbcat(&bytes, &stem).map_err(|e| io_err(path, e))
120    }
121}
122
123/// 外部のレンズカタログを読む実装が満たすトレイト。
124pub trait LensCatalogSource {
125    /// この実装が読める拡張子(小文字、ドットなし)。
126    fn extensions(&self) -> &[&str];
127    /// ファイルを読み、レンズの一覧を返す(読めなければ `Error::Io`、中身の誤りは `Error::Invalid` など)。
128    fn load(&self, path: &Path) -> Result<Vec<CatalogLens>>;
129}
130
131/// path を読めなかった誤り(`<path>: <理由>`)
132fn io_err(path: &Path, e: impl std::fmt::Display) -> Error {
133    Error::Io(format!("{}: {e}", path.display()))
134}
135
136/// .zmx 1 つを 1 レンズとするカタログ(自作のレンズや、カタログから書き出したレンズ)。
137/// メーカーは親フォルダの名前、型番はファイル名(拡張子なし)。焦点距離はカタログの値がないので NaN。
138pub struct ZmxFileSource;
139
140impl LensCatalogSource for ZmxFileSource {
141    fn extensions(&self) -> &[&str] {
142        &["zmx"]
143    }
144    fn load(&self, path: &Path) -> Result<Vec<CatalogLens>> {
145        let zmx = crate::glass::read_text(path).map_err(|e| io_err(path, e))?;
146        let name = |p: Option<&Path>| {
147            p.and_then(|p| p.file_name())
148                .map(|s| s.to_string_lossy().into_owned())
149                .unwrap_or_default()
150        };
151        let part = path
152            .file_stem()
153            .map(|s| s.to_string_lossy().into_owned())
154            .unwrap_or_default();
155        // 相対パスでも親フォルダの名前が取れるように、絶対パスにしてから見る
156        let abs = crate::vfs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
157        Ok(vec![CatalogLens {
158            vendor: name(abs.parent()),
159            part,
160            efl: f64::NAN,
161            zmx,
162        }])
163    }
164}
165
166/// paths(ファイルかフォルダ)から読むカタログのファイルと、それを読む source の番号(読む順)。
167/// フォルダは中のファイル(1 階層。カタログのファイルが 1 つも無ければメーカーのフォルダの親とみて 1 段下も)を
168/// 名前の順に。フォルダの中の関係のないファイルは飛ばし、直に渡したファイルの形式が読めなければ誤り
169fn catalog_files(
170    paths: &[std::path::PathBuf],
171    sources: &[&dyn LensCatalogSource],
172) -> Result<Vec<(std::path::PathBuf, usize)>> {
173    let source_of = |f: &std::path::Path| {
174        let ext = f
175            .extension()
176            .map(|x| x.to_string_lossy().to_ascii_lowercase())
177            .unwrap_or_default();
178        sources
179            .iter()
180            .position(|s| s.extensions().contains(&ext.as_str()))
181    };
182    let mut out = Vec::new();
183    for p in paths {
184        if !crate::vfs::is_dir(p) {
185            match source_of(p) {
186                Some(s) => out.push((p.clone(), s)),
187                None => {
188                    return Err(Error::Invalid(format!(
189                        "{}: a lens catalog in a format that can't be read",
190                        p.display()
191                    )))
192                }
193            }
194            continue;
195        }
196        let rd = crate::vfs::read_dir(p).map_err(|e| io_err(p, e))?;
197        let mut files: Vec<std::path::PathBuf> = rd
198            .iter()
199            .filter(|f| crate::vfs::is_file(f))
200            .cloned()
201            .collect();
202        if !files.iter().any(|f| source_of(f).is_some()) {
203            for d in rd.iter().filter(|d| crate::vfs::is_dir(d)) {
204                if let Ok(sub) = crate::vfs::read_dir(d) {
205                    files.extend(sub.into_iter().filter(|f| crate::vfs::is_file(f)));
206                }
207            }
208        }
209        files.sort();
210        out.extend(
211            files
212                .into_iter()
213                .filter_map(|f| source_of(&f).map(|s| (f, s))),
214        );
215    }
216    Ok(out)
217}
218
219/// メーカー名の鍵: 英数字だけを大文字にしたもの("EDMUND OPTICS" と "Edmund_Optics" は同じ)。メーカー名を比べる所は
220/// 全部これを使う(以前は大文字にするだけ・英数字だけ・大文字の「含む」の 3 通りがあった)。
221/// 同じメーカーかは鍵の一致、人が書いた名前での絞り込み(検索・差し替え探索・公差)は [`VendorKey::matches`]
222#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
223pub struct VendorKey(String);
224
225impl VendorKey {
226    pub fn new(name: &str) -> VendorKey {
227        VendorKey(
228            name.chars()
229                .filter(|c| c.is_alphanumeric())
230                .flat_map(char::to_uppercase)
231                .collect(),
232        )
233    }
234    pub fn as_str(&self) -> &str {
235        &self.0
236    }
237    /// 鍵が空(名前が無いか、英数字を含まない)
238    pub fn is_empty(&self) -> bool {
239        self.0.is_empty()
240    }
241    /// 人が書いた名前 `pat` の絞り込みに合う: 鍵が `pat` の鍵を含む("edmund" は "Edmund Optics" に合う)。
242    /// 空の `pat` はすべてに合う
243    pub fn matches(&self, pat: &VendorKey) -> bool {
244        self.0.contains(&pat.0)
245    }
246}
247
248/// 読み込んだレンズカタログの集まり。メーカーは [`VendorKey`] で、型番は前後の空白と大文字・小文字を区別しない。
249#[derive(Debug, Clone, Default)]
250pub struct LensCatalog {
251    lenses: Vec<CatalogLens>,
252    index: std::collections::HashMap<(VendorKey, String), usize>,
253}
254
255impl LensCatalog {
256    /// ファイルまたはフォルダ(中のファイル、1 階層)を、拡張子が合う source で読む。
257    /// 同じメーカー・型番は後に読んだものを使う。
258    pub fn load(
259        paths: &[std::path::PathBuf],
260        sources: &[&dyn LensCatalogSource],
261    ) -> Result<LensCatalog> {
262        let mut c = LensCatalog::default();
263        for (f, s) in catalog_files(paths, sources)? {
264            for l in sources[s].load(&f)? {
265                c.add(l);
266            }
267        }
268        Ok(c)
269    }
270
271    /// [`load`](Self::load) を、今の拡張の表の形式([`crate::ext::current`])で。読んだものを読んだファイルの
272    /// 更新時刻・大きさと共に覚えておき、どれも変わっていなければ読み直さない(以前は呼ぶたびにフォルダの
273    /// 全カタログを読み直した)。フォルダにファイルが増えた・減ったときも読み直す
274    pub fn load_registered(paths: &[std::path::PathBuf]) -> Result<std::sync::Arc<LensCatalog>> {
275        use crate::sync::LockExt;
276        use std::sync::{Arc, Mutex, OnceLock};
277        type Key = (Vec<std::path::PathBuf>, Vec<String>);
278        type Stamps = Vec<(std::path::PathBuf, crate::vfs::Stamp)>;
279        type Cache = std::collections::HashMap<Key, (Stamps, Arc<LensCatalog>)>;
280        static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
281        let src = crate::ext::current().catalog_sources();
282        let refs: Vec<&dyn LensCatalogSource> = src
283            .iter()
284            .map(|s| s.as_ref() as &dyn LensCatalogSource)
285            .collect();
286        let files = catalog_files(paths, &refs)?;
287        // 更新時刻が取れないファイルがあれば覚えずに読む
288        let stamps: Option<Stamps> = files
289            .iter()
290            .map(|(f, _)| crate::vfs::stamp(f).ok().map(|st| (f.clone(), st)))
291            .collect();
292        let Some(stamps) = stamps else {
293            return Self::load(paths, &refs).map(Arc::new);
294        };
295        let exts = refs
296            .iter()
297            .flat_map(|s| s.extensions().iter().map(|e| e.to_string()))
298            .collect();
299        let key: Key = (paths.to_vec(), exts);
300        let cache = CACHE.get_or_init(Default::default);
301        if let Some((st, c)) = cache.lock_ok().get(&key) {
302            if *st == stamps {
303                return Ok(c.clone());
304            }
305        }
306        let mut c = LensCatalog::default();
307        for (f, s) in &files {
308            for l in refs[*s].load(f)? {
309                c.add(l);
310            }
311        }
312        let c = Arc::new(c);
313        cache.lock_ok().insert(key, (stamps, c.clone()));
314        Ok(c)
315    }
316
317    fn key(vendor: &str, part: &str) -> (VendorKey, String) {
318        (VendorKey::new(vendor), part.trim().to_uppercase())
319    }
320
321    pub fn add(&mut self, l: CatalogLens) {
322        let k = Self::key(&l.vendor, &l.part);
323        match self.index.get(&k) {
324            Some(&i) => self.lenses[i] = l,
325            None => {
326                self.index.insert(k, self.lenses.len());
327                self.lenses.push(l);
328            }
329        }
330    }
331
332    pub fn get(&self, vendor: &str, part: &str) -> Option<&CatalogLens> {
333        self.index
334            .get(&Self::key(vendor, part))
335            .map(|&i| &self.lenses[i])
336    }
337
338    /// (メーカー, 型番) → .zmx の本文(プロジェクトの展開に渡す形)
339    pub fn zmx(&self, vendor: &str, part: &str) -> crate::Result<String> {
340        Ok(self
341            .get(vendor, part)
342            .map(|l| l.zmx.clone())
343            .ok_or_else(|| format!(
344                "no {vendor} {part} in the lens catalogs. Pass lens catalog folders with --lens-catalog (CLI) or lens_catalogs (serve, Python)"
345            ))?)
346    }
347
348    pub fn lenses(&self) -> &[CatalogLens] {
349        &self.lenses
350    }
351
352    pub fn len(&self) -> usize {
353        self.lenses.len()
354    }
355
356    pub fn is_empty(&self) -> bool {
357        self.lenses.is_empty()
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364
365    /// .lbcat は書いたとおりに読み戻せる(焦点距離のビット・数でない値・複数行と非 ASCII の .zmx・空の束)
366    #[test]
367    fn lbcat_round_trips() {
368        let lenses = vec![
369            CatalogLens {
370                vendor: "V".into(),
371                part: "A-1".into(),
372                efl: 0.1 + 0.2,
373                zmx: "VERS 1\nNAME A-1\r\nGLAS N-BK7 µ\n".into(),
374            },
375            CatalogLens {
376                vendor: "V".into(),
377                part: "B 2".into(),
378                efl: f64::NAN,
379                zmx: String::new(),
380            },
381        ];
382        let b = encode_lbcat("ACME", "ACME.ZMF", &lenses).unwrap();
383        let r = decode_lbcat(&b, "fallback").unwrap();
384        assert_eq!(r.len(), 2);
385        assert_eq!(r[0].vendor, "ACME");
386        assert_eq!(r[0].part, "A-1");
387        assert_eq!(r[0].efl.to_bits(), (0.1f64 + 0.2).to_bits());
388        assert_eq!(r[0].zmx, lenses[0].zmx);
389        assert!(r[1].efl.is_nan() && r[1].zmx.is_empty() && r[1].part == "B 2");
390        let e = decode_lbcat(&encode_lbcat("", "x", &[]).unwrap(), "STEM").unwrap();
391        assert!(e.is_empty());
392        let one = encode_lbcat("", "x", &lenses[..1]).unwrap();
393        assert_eq!(decode_lbcat(&one, "STEM").unwrap()[0].vendor, "STEM");
394        assert!(encode_lbcat("A\tB", "x", &[]).is_err());
395        assert!(decode_lbcat(b"not zlib", "x").is_err());
396        // 壊れた束(.zmx のバイト数が巨大)は誤りで返す(桁あふれで落ちない)
397        let bad = format!("LBCAT 1\tV\tS\nA\t1\t{}\n", usize::MAX);
398        let z = miniz_oxide::deflate::compress_to_vec_zlib(bad.as_bytes(), 6);
399        assert!(decode_lbcat(&z, "x").is_err());
400    }
401
402    #[test]
403    fn vendor_key_ignores_case_spaces_and_symbols() {
404        let k = VendorKey::new("Edmund_Optics");
405        assert_eq!(k, VendorKey::new("EDMUND OPTICS"));
406        assert_eq!(k.as_str(), "EDMUNDOPTICS");
407        assert!(k.matches(&VendorKey::new("edmund")));
408        assert!(k.matches(&VendorKey::new("")));
409        assert!(!k.matches(&VendorKey::new("Thorlabs")));
410        let mut c = LensCatalog::default();
411        c.add(CatalogLens {
412            vendor: "Edmund Optics".into(),
413            part: " 32-317 ".into(),
414            efl: 1.0,
415            zmx: String::new(),
416        });
417        assert!(c.get("EDMUND-OPTICS", "32-317").is_some());
418    }
419
420    /// 覚えたカタログは、ファイルを書き換える・足すと読み直す
421    #[test]
422    fn load_registered_rereads_changed_files() {
423        let fs = std::sync::Arc::new(crate::vfs::MemFs::new());
424        crate::vfs::with(fs, || {
425            let d = std::path::PathBuf::from("/cat/ACME");
426            crate::vfs::write(d.join("A.zmx"), "VERS 1\n").unwrap();
427            let a = LensCatalog::load_registered(std::slice::from_ref(&d)).unwrap();
428            let b = LensCatalog::load_registered(std::slice::from_ref(&d)).unwrap();
429            assert!(std::sync::Arc::ptr_eq(&a, &b));
430            assert_eq!(a.len(), 1);
431            crate::vfs::write(d.join("B.zmx"), "VERS 1\n").unwrap();
432            let c = LensCatalog::load_registered(std::slice::from_ref(&d)).unwrap();
433            assert_eq!(c.len(), 2);
434            crate::vfs::write(d.join("A.zmx"), "VERS 1\nNAME longer\n").unwrap();
435            let e = LensCatalog::load_registered(std::slice::from_ref(&d)).unwrap();
436            assert!(!std::sync::Arc::ptr_eq(&c, &e));
437            assert!(e.zmx("acme", "a").unwrap().contains("longer"));
438        });
439    }
440}