Skip to main content

lensbench_catalog/
fill.rs

1//! カタログの「未完の品」(厚さ・径の足りない品)を補う。
2//!
3//! 未完の品([`lensbench_project::UserItem::is_incomplete`])は blocks を持たず、分かっている仕様・品ページの URL・
4//! 足りない値の名前(`missing`)だけを持つ。ユーザーが品を選んだときに品ページを 1 件だけ開き、
5//! - 仕様表の文字(`Thickness (mm): 3.00` など)を [`read_page`] で読むか、
6//! - CAD 欄から落とした STEP を [`crate::step::read_step`] で測り、
7//!
8//! ユーザーが確かめた値で [`complete`] が普通の品(blocks つき)を作る。作った品はユーザー側のカタログ
9//! (補足のカタログ)に保存し、次からは普通の品として並べる(元のカタログは書き換えない)。
10
11use crate::step::StepSize;
12use lensbench_project::UserItem;
13use serde_json::{json, Value};
14
15/// 補える値の名前
16pub const FILLABLE: [&str; 2] = ["thickness", "diameter"];
17
18/// 仕様表から読んだ 1 欄
19#[derive(Debug, Clone, PartialEq)]
20pub struct Reading {
21    /// 値の名前(`thickness`・`diameter`、枠の `mount_thickness`・`mount_diameter`・`clear_aperture`)
22    pub name: &'static str,
23    /// ページの欄の名前(`Thickness (mm)` など)
24    pub label: String,
25    /// 欄の値の文字
26    pub raw: String,
27    /// 読めた値 [mm](径は数か [幅, 高さ])。値が 2 つ以上並ぶなど決められないときは None
28    pub value: Option<Value>,
29}
30
31/// 仕様表の読み取りの結果
32#[derive(Debug, Clone, Default, PartialEq)]
33pub struct PageRead {
34    /// 厚さ [mm]
35    pub thickness: Option<f64>,
36    /// 径 [mm](数か [幅, 高さ])
37    pub diameter: Option<Value>,
38    /// 枠付きの品の枠の厚さ・外径、有効径 [mm]([`page_frame`])
39    pub mount_thickness: Option<f64>,
40    pub mount_diameter: Option<f64>,
41    pub clear_aperture: Option<f64>,
42    /// 見つけた欄(値の読めなかった欄も。ユーザーに見せる)
43    pub found: Vec<Reading>,
44}
45
46impl PageRead {
47    /// 名前の値(`thickness`・`diameter`)
48    pub fn get(&self, name: &str) -> Option<Value> {
49        match name {
50            "thickness" => self.thickness.map(|x| json!(x)),
51            "diameter" => self.diameter.clone(),
52            "mount_thickness" => self.mount_thickness.map(|x| json!(x)),
53            "mount_diameter" => self.mount_diameter.map(|x| json!(x)),
54            "clear_aperture" => self.clear_aperture.map(|x| json!(x)),
55            _ => None,
56        }
57    }
58}
59
60/// ページの文字のうち見る長さの上限(大きなページでも止まらない)
61const MAX_TEXT: usize = 4 << 20;
62
63/// 欄の名前(小文字・末尾の `:` を除いたもの)が、どの値の欄か。優先度(小さいほど先)も返す
64fn label_kind(label: &str) -> Option<(&'static str, u8)> {
65    let l = label
66        .trim()
67        .trim_end_matches(':')
68        .trim()
69        .to_ascii_lowercase();
70    // 欄の名前は短い(長い行は説明の文)
71    if l.is_empty() || l.len() > 48 {
72        return None;
73    }
74    // 枠(マウント・ハウジング)の厚さ・外径と有効径
75    let head0 = l.split('(').next().unwrap_or("").trim();
76    let frame = match head0 {
77        "mount thickness" | "housing thickness" | "mounted thickness" | "mount thickness t" => {
78            Some(("mount_thickness", 0))
79        }
80        "mount diameter"
81        | "mount outer diameter"
82        | "housing diameter"
83        | "mounted diameter"
84        | "housing outer diameter"
85        | "mount od" => Some(("mount_diameter", 0)),
86        "clear aperture" | "clear aperture ca" | "ca" => Some(("clear_aperture", 0)),
87        _ => None,
88    };
89    if let Some(f) = frame {
90        return (head0.len() == l.len() || l[head0.len()..].trim_start().starts_with('('))
91            .then_some(f);
92    }
93    let bad = [
94        "mount",
95        "housing",
96        "tolerance",
97        "cell",
98        "edge thickness",
99        "total",
100        "frame",
101        "clear aperture",
102        "beam",
103        "minor",
104        "major",
105        "wedge",
106        "coating",
107        "ring",
108        "thread",
109    ];
110    if bad.iter().any(|b| l.contains(b)) {
111        return None;
112    }
113    let head = l.split('(').next().unwrap_or("").trim();
114    let t = match head {
115        "thickness" | "substrate thickness" | "thickness t" => Some(("thickness", 0)),
116        "center thickness" | "center thickness ct" | "ct" => Some(("thickness", 1)),
117        "diameter" | "outer diameter" | "diameter d" | "outside diameter" => Some(("diameter", 0)),
118        "dimensions" | "size" | "dimension" => Some(("diameter", 1)),
119        _ => None,
120    };
121    // 単位の書かれた欄か、名前だけの欄(`Thickness:`)
122    t.filter(|_| head.len() == l.len() || l[head.len()..].trim_start().starts_with('('))
123}
124
125/// 欄の単位の倍率(mm へ)。欄の名前の `(mm)`・`(in)`、無ければ値の単位
126fn unit_scale(label: &str, raw: &str) -> f64 {
127    let l = label.to_ascii_lowercase();
128    if l.contains("(mm)") || l.contains("mm)") {
129        return 1.0;
130    }
131    if l.contains("(in") || l.contains("inch") {
132        return 25.4;
133    }
134    let r = raw.to_ascii_lowercase();
135    if r.contains("mm") {
136        1.0
137    } else if r.contains('"') || r.contains("inch") || inch_after_number(&r) {
138        25.4
139    } else {
140        1.0
141    }
142}
143
144/// 数の直後の `in`(`0.25 in`・`0.25in`)。`3.0 including` のような語の頭は数えない
145fn inch_after_number(r: &str) -> bool {
146    let b = r.as_bytes();
147    numbers(r).iter().any(|&(st, _)| {
148        let mut i = st;
149        while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.') {
150            i += 1;
151        }
152        while i < b.len() && b[i] == b' ' {
153            i += 1;
154        }
155        b[i..].starts_with(b"in") && b.get(i + 2).is_none_or(|c| !c.is_ascii_alphabetic())
156    })
157}
158
159/// 文字の中の数(符号のない小数)を順に
160fn numbers(s: &str) -> Vec<(usize, f64)> {
161    let b = s.as_bytes();
162    let mut out = Vec::new();
163    let mut i = 0;
164    while i < b.len() {
165        if b[i].is_ascii_digit() || (b[i] == b'.' && i + 1 < b.len() && b[i + 1].is_ascii_digit()) {
166            let st = i;
167            while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.') {
168                i += 1;
169            }
170            if let Ok(x) = s[st..i].trim_end_matches('.').parse::<f64>() {
171                out.push((st, x));
172            }
173        } else {
174            i += 1;
175        }
176    }
177    out
178}
179
180/// 欄の値の文字から値 [mm] を読む。許容差(`±0.1`・`+0.00/-0.10`)は捨て、公称値が 2 つ以上
181/// (`2.00 & 3.00`)なら決めない。径の欄は `25 x 25` を [幅, 高さ] に
182fn parse_value(name: &str, label: &str, raw: &str) -> Option<Value> {
183    let k = unit_scale(label, raw);
184    // 許容差の始まり(±・+・-)より前だけを公称値として見る。`x`・`×` で並ぶのは寸法
185    let cut = raw
186        .char_indices()
187        .find(|&(_, c)| matches!(c, '±' | '+' | '-' | '−' | '('))
188        .map_or(raw.len(), |(i, _)| i);
189    let nominal = &raw[..cut];
190    let nums = numbers(nominal);
191    if nums.is_empty() {
192        return None;
193    }
194    let lower = nominal.to_ascii_lowercase();
195    let is_dims = lower.contains(" x ") || lower.contains('×') || lower.contains("x");
196    let several = nums.len() > 1;
197    if several && !(name == "diameter" && is_dims && nums.len() == 2) {
198        return None;
199    }
200    if name == "diameter" && nums.len() == 2 {
201        let (a, b) = (nums[0].1 * k, nums[1].1 * k);
202        if (a - b).abs() < 1e-9 {
203            return Some(json!(round6(a)));
204        }
205        return Some(json!([round6(a), round6(b)]));
206    }
207    let x = nums[0].1 * k;
208    (x > 0.0 && x.is_finite()).then(|| json!(round6(x)))
209}
210
211fn round6(x: f64) -> f64 {
212    (x * 1e6).round() / 1e6
213}
214
215/// 品ページの文字(ブラウザの `document.body.innerText`、またはページを選んで写した文字)から厚さ・径を読む。
216/// 欄の名前の行に値が無ければ次の空でない行を値とみる。欄が無いページでは何も返さない(止まらない)
217pub fn read_page(text: &str) -> PageRead {
218    let text = if text.len() > MAX_TEXT {
219        let mut e = MAX_TEXT;
220        while !text.is_char_boundary(e) {
221            e -= 1;
222        }
223        &text[..e]
224    } else {
225        text
226    };
227    let lines: Vec<&str> = text.lines().map(str::trim).collect();
228    let mut out = PageRead::default();
229    let mut best: [Option<(u8, Value)>; 5] = Default::default();
230    for (i, line) in lines.iter().enumerate() {
231        // `欄: 値`・`欄\t値`・`欄`(値は次の行)
232        let (label, rest) = match line.find(':') {
233            Some(c) => (&line[..c], line[c + 1..].trim()),
234            None => match line.find('\t') {
235                Some(c) => (&line[..c], line[c + 1..].trim()),
236                None => (*line, ""),
237            },
238        };
239        let Some((name, prio)) = label_kind(label) else {
240            continue;
241        };
242        // 名前だけの行(`Thickness`)は、表の欄として `:` かタブがあるか次の行が値のときだけ
243        let raw = if rest.is_empty() {
244            match lines[i + 1..].iter().find(|x| !x.is_empty()) {
245                Some(n) if label_kind(n.split(':').next().unwrap_or("")).is_none() => *n,
246                _ => continue,
247            }
248        } else {
249            rest
250        };
251        if raw.len() > 80 || numbers(raw).is_empty() {
252            continue;
253        }
254        // 有効径の「90%」などは寸法でない
255        let value = if raw.contains('%') {
256            None
257        } else {
258            parse_value(name, label, raw)
259        };
260        let slot = match name {
261            "thickness" => 0,
262            "diameter" => 1,
263            "mount_thickness" => 2,
264            "mount_diameter" => 3,
265            _ => 4,
266        };
267        if let Some(v) = &value {
268            if best[slot].as_ref().is_none_or(|(p, _)| prio < *p) {
269                best[slot] = Some((prio, v.clone()));
270            }
271        }
272        out.found.push(Reading {
273            name,
274            label: label.trim().to_string(),
275            raw: raw.to_string(),
276            value,
277        });
278    }
279    out.thickness = best[0].take().and_then(|(_, v)| v.as_f64());
280    out.diameter = best[1].take().map(|(_, v)| v);
281    out.mount_thickness = best[2].take().and_then(|(_, v)| v.as_f64());
282    out.mount_diameter = best[3].take().and_then(|(_, v)| v.as_f64());
283    out.clear_aperture = best[4].take().and_then(|(_, v)| v.as_f64());
284    out
285}
286
287/// 仕様表の枠の厚さ・外径(無ければ径の欄)・有効径から、枠付きの品の簡単な枠(長さ全体で有効径の穴)。
288/// 座の位置は仕様表から分からないので、厚さ `thickness` のガラスを枠の中央に置く。ガラスの径 `glass` が
289/// 分かれば保持径にする。値が足りない・外径が有効径以下なら None
290pub fn page_frame(
291    r: &PageRead,
292    thickness: Option<f64>,
293    glass: Option<f64>,
294) -> Option<lensbench_project::MechSpec> {
295    let len = r.mount_thickness.filter(|x| *x > 0.0)?;
296    let ca = r.clear_aperture.filter(|x| *x > 0.0)?;
297    let od = r
298        .mount_diameter
299        .or_else(|| r.diameter.as_ref().and_then(Value::as_f64))
300        .filter(|x| *x > ca)?;
301    let seat = thickness
302        .filter(|t| *t > 0.0 && *t <= len)
303        .map_or(0.0, |t| round6((len - t) / 2.0));
304    Some(lensbench_project::MechSpec {
305        bores: vec![lensbench_project::BoreSpec {
306            z0: 0.0,
307            z1: len,
308            diameter: ca,
309        }],
310        length: len,
311        outer_diameter: od,
312        holds: Some(lensbench_project::HoldSpec {
313            diameter: glass.filter(|g| *g >= ca && *g <= od).unwrap_or(ca),
314            seat_z: seat,
315            max_diameter: 0.0,
316        }),
317        ..Default::default()
318    })
319}
320
321/// 仕様表の値(STEP で分けた寸法と突き合わせる [`spec_check`])[mm]
322#[derive(Clone, Copy, Debug, Default, PartialEq)]
323pub struct SpecValues {
324    pub thickness: Option<f64>,
325    pub diameter: Option<f64>,
326    pub mount_thickness: Option<f64>,
327    pub mount_diameter: Option<f64>,
328    pub clear_aperture: Option<f64>,
329}
330
331impl SpecValues {
332    /// 読んだ仕様表の値を先に、無い値は品の `specs` から
333    pub fn of(specs: &serde_json::Map<String, Value>, page: Option<&PageRead>) -> Self {
334        let get = |k: &str| {
335            page.and_then(|p| p.get(k))
336                .or_else(|| specs.get(k).cloned())
337                .and_then(|v| v.as_f64())
338                .filter(|x| *x > 0.0 && x.is_finite())
339        };
340        SpecValues {
341            thickness: get("thickness"),
342            diameter: get("diameter"),
343            mount_thickness: get("mount_thickness"),
344            mount_diameter: get("mount_diameter"),
345            clear_aperture: get("clear_aperture"),
346        }
347    }
348
349    /// serve の params(`{"thickness": …, …}`)から
350    pub fn from_value(v: &Value) -> Self {
351        let m = v.as_object().cloned().unwrap_or_default();
352        Self::of(&m, None)
353    }
354
355    pub fn to_value(&self) -> Value {
356        let mut m = serde_json::Map::new();
357        for (k, v) in [
358            ("thickness", self.thickness),
359            ("diameter", self.diameter),
360            ("mount_thickness", self.mount_thickness),
361            ("mount_diameter", self.mount_diameter),
362            ("clear_aperture", self.clear_aperture),
363        ] {
364            if let Some(v) = v {
365                m.insert(k.into(), json!(v));
366            }
367        }
368        Value::Object(m)
369    }
370
371    /// 枠付きの品で、仕様の厚さ・径が枠の値か(枠の厚さ・外径の欄が無く、枠の長さ・外径と合う)。
372    /// Thorlabs のマウント付きフィルタなどは「厚さ」「径」が枠の値
373    fn frame_valued(&self, frame: Option<&lensbench_project::MechSpec>) -> (bool, bool) {
374        let Some(f) = frame else {
375            return (false, false);
376        };
377        let near = |a: Option<f64>, b: f64| a.is_some_and(|a| (a - b).abs() <= SPEC_TOL);
378        (
379            self.mount_thickness.is_none() && near(self.thickness, f.length),
380            self.mount_diameter.is_none() && near(self.diameter, f.outer_diameter),
381        )
382    }
383}
384
385/// STEP と仕様表の値が同じとみなす差 [mm](図面の寸法の丸め程度)
386pub const SPEC_TOL: f64 = 0.05;
387
388/// STEP の値と仕様表の値の突き合わせ 1 項目
389#[derive(Clone, Copy, Debug, PartialEq)]
390pub struct SpecCmp {
391    /// 項目(`thickness`・`diameter` はガラス、`mount_thickness`・`mount_diameter`・`clear_aperture` は枠)
392    pub key: &'static str,
393    pub step: f64,
394    pub spec: f64,
395    /// 仕様の値の欄(枠の値を「厚さ」「径」の欄に書く品では `thickness`・`diameter`)
396    pub spec_key: &'static str,
397}
398
399impl SpecCmp {
400    /// 合うか。有効径は品質を保証する範囲で、枠の穴(機構の開口)より小さいのが普通なので、仕様の値が穴より
401    /// 大きい時だけ食い違いとする
402    pub fn ok(&self) -> bool {
403        if self.key == "clear_aperture" {
404            self.spec <= self.step + SPEC_TOL
405        } else {
406            (self.step - self.spec).abs() <= SPEC_TOL
407        }
408    }
409
410    /// 項目の名前(ユーザーに見せる)
411    pub fn label(&self) -> &'static str {
412        match self.key {
413            "thickness" => "glass thickness",
414            "diameter" => "glass diameter",
415            "mount_thickness" => "mount thickness",
416            "mount_diameter" => "mount outer diameter",
417            _ => "clear aperture",
418        }
419    }
420
421    /// 食い違いの説明(保存する品の notes に書く)
422    pub fn note(&self) -> String {
423        format!(
424            "{what}: STEP {} mm, spec table {} mm (difference {} mm)",
425            round6(self.step),
426            round6(self.spec),
427            round6(self.step - self.spec),
428            what = self.label(),
429        )
430    }
431}
432
433/// STEP で測ったガラス(厚さ・径)と枠を、仕様表の値と突き合わせる。比べられる項目だけを返す。
434/// 枠付きの品で仕様の「厚さ」「径」が枠の長さ・外径と合えば、それらは枠の値として比べる。
435/// ガラスと枠が 1 つの立体(`merged`)のガラスの径は見えている径なので、仕様の径とは比べない
436pub fn spec_check(
437    thickness: Option<f64>,
438    diameter: Option<f64>,
439    frame: Option<&lensbench_project::MechSpec>,
440    merged: bool,
441    s: &SpecValues,
442) -> Vec<SpecCmp> {
443    let (ft, fd) = s.frame_valued(frame);
444    let mut out = Vec::new();
445    let mut push = |key, step: Option<f64>, spec: Option<f64>, spec_key| {
446        if let (Some(step), Some(spec)) = (step, spec) {
447            out.push(SpecCmp {
448                key,
449                step,
450                spec,
451                spec_key,
452            });
453        }
454    };
455    if !ft {
456        push("thickness", thickness, s.thickness, "thickness");
457    }
458    if !fd && !merged {
459        push("diameter", diameter, s.diameter, "diameter");
460    }
461    if let Some(f) = frame {
462        let (mt, mtk) = if ft {
463            (s.thickness, "thickness")
464        } else {
465            (s.mount_thickness, "mount_thickness")
466        };
467        push("mount_thickness", Some(f.length), mt, mtk);
468        let (md, mdk) = if fd {
469            (s.diameter, "diameter")
470        } else {
471            (s.mount_diameter, "mount_diameter")
472        };
473        push("mount_diameter", Some(f.outer_diameter), md, mdk);
474        let clear = f
475            .bores
476            .iter()
477            .map(|b| b.diameter)
478            .fold(f64::INFINITY, f64::min);
479        push(
480            "clear_aperture",
481            clear.is_finite().then_some(clear),
482            s.clear_aperture,
483            "clear_aperture",
484        );
485    }
486    out
487}
488
489/// ガラスと枠が 1 つの立体の STEP で、STEP から分からないガラスの本当の径を仕様表で補う。
490/// 仕様の径が枠の値でなく、見えている径以上で枠の外径より小さければその値
491pub fn spec_glass_diameter(
492    visible: f64,
493    frame: &lensbench_project::MechSpec,
494    s: &SpecValues,
495) -> Option<f64> {
496    let (_, fd) = s.frame_valued(Some(frame));
497    s.diameter
498        .filter(|_| !fd)
499        .filter(|d| *d >= visible - SPEC_TOL && *d < frame.outer_diameter)
500}
501
502/// 品の簡易外形(カタログの `mech`)と、取った STEP から測った寸法の食い違い(長さ・外径・外形の形)。
503/// 食い違いの説明の並び(空なら合う)。差は [`SPEC_TOL`] まで許す
504pub fn cad_check(mech: &lensbench_project::MechSpec, s: &StepSize) -> Vec<String> {
505    let mut v = Vec::new();
506    let Some(f) = s.frame.as_ref().filter(|_| s.mech) else {
507        return vec!["the mechanical dimensions can't be measured from the STEP (it has glass, no bore, or the like)".into()];
508    };
509    for (label, cat, step) in [
510        ("length", mech.length, f.length),
511        ("outer diameter", mech.outer_diameter, f.outer_diameter),
512    ] {
513        if cat > 0.0 && (cat - step).abs() > SPEC_TOL {
514            v.push(format!(
515                "{what}: catalog {} mm, STEP {} mm (difference {} mm)",
516                cat,
517                step,
518                round6(step - cat),
519                what = label,
520            ));
521        }
522    }
523    if mech.outline != f.outline {
524        v.push(
525            match (mech.outline.is_round(), f.outline.is_round()) {
526                (true, true) => "outline: catalog round, STEP round",
527                (true, false) => "outline: catalog round, STEP square",
528                (false, true) => "outline: catalog square, STEP round",
529                (false, false) => "outline: catalog square, STEP square",
530            }
531            .to_string(),
532        );
533    }
534    v
535}
536
537/// 基板の名前から硝材(名前・ガラスのカタログ)。分からない基板は N-BK7 で代用し、代用なら true
538pub fn material_glass(material: &str) -> (&'static str, &'static str, bool) {
539    let m = material.to_ascii_lowercase();
540    let has = |k: &str| m.contains(k);
541    if has("fused silica") || has("7980") || has("fused quartz") || has("uvfs") {
542        ("F_SILICA", "MISC", false)
543    } else if has("n-bk7") || m.trim() == "bk7" || has("bk7") {
544        ("N-BK7", "SCHOTT", false)
545    } else if has("b270") || has("b 270") {
546        ("B270", "SCHOTT", false)
547    } else if has("caf2") || has("calcium fluoride") {
548        ("CAF2", "MISC", false)
549    } else if has("sapphire") {
550        ("SAPPHIRE", "INFRARED", false)
551    } else if has("baf2") || has("barium fluoride") {
552        ("BAF2", "INFRARED", false)
553    } else if has("germanium") {
554        ("GERMANIUM", "INFRARED", false)
555    } else if has("silicon") {
556        ("SILICON", "INFRARED", false)
557    } else if has("mgf2") || has("magnesium fluoride") {
558        ("MGF2", "INFRARED", false)
559    } else if has("znse") || has("zinc selenide") {
560        ("ZNSE", "INFRARED", false)
561    } else {
562        ("N-BK7", "SCHOTT", true)
563    }
564}
565
566/// 値の決め方(補足のメモに書く)
567#[derive(Debug, Clone, Copy, PartialEq, Eq)]
568pub enum FillFrom {
569    /// 品ページの仕様表
570    Page,
571    /// 品ページの CAD(STEP)
572    Step,
573    /// ユーザーの入力
574    Manual,
575}
576
577impl FillFrom {
578    pub fn parse(s: &str) -> FillFrom {
579        match s {
580            "page" => FillFrom::Page,
581            "step" => FillFrom::Step,
582            _ => FillFrom::Manual,
583        }
584    }
585    fn text(self) -> &'static str {
586        match self {
587            FillFrom::Page => "the spec table of the product page",
588            FillFrom::Step => "the STEP of the product page",
589            FillFrom::Manual => "the user input",
590        }
591    }
592}
593
594/// 径の値(数か [幅, 高さ])の半径(四角は長い辺の半分)
595fn semi_of(d: &Value) -> Option<f64> {
596    let x = match d {
597        Value::Number(n) => n.as_f64()?,
598        Value::Array(a) => a.iter().filter_map(Value::as_f64).fold(0.0, f64::max),
599        _ => return None,
600    };
601    (x > 0.0 && x.is_finite()).then_some(x / 2.0)
602}
603
604/// 未完の品に足りない値を足して、普通の品(blocks つき)にする。
605///
606/// `thickness`・`diameter` は足りない値(`missing`)の分が要る(ほかは品の specs のまま)。
607/// 鏡は平面鏡、ほかは基板(`specs.material`)の平行平板(分からない基板は N-BK7 で代用し、notes に書く)。
608/// `checked` は値を確かめた日(YYYY-MM-DD)。`frame` は枠付きの品の枠([`StepSize::frame`]・[`page_frame`])で、
609/// 品の `frame` に入れる(有効径 `clear_aperture` が無ければ枠の最小の内径を入れる)
610pub fn complete(
611    item: &UserItem,
612    thickness: Option<f64>,
613    diameter: Option<Value>,
614    frame: Option<lensbench_project::MechSpec>,
615    from: FillFrom,
616    checked: &str,
617) -> lensbench_core::Result<UserItem> {
618    use lensbench_project::catalog_spec::ItemKind;
619    let mut it = item.clone();
620    for m in item.missing() {
621        let ok = match m.as_str() {
622            "thickness" => thickness.is_some_and(|t| t > 0.0 && t.is_finite()),
623            "diameter" => diameter.as_ref().and_then(semi_of).is_some(),
624            other => return Err(format!("value that can't be filled in: {other}").into()),
625        };
626        if !ok {
627            return Err(format!("a value for {m} is needed").into());
628        }
629    }
630    if let Some(t) = thickness.filter(|t| *t > 0.0 && t.is_finite()) {
631        it.specs.insert("thickness".into(), json!(t));
632    }
633    if let Some(d) = diameter.filter(|d| semi_of(d).is_some()) {
634        it.specs.insert("diameter".into(), d);
635    }
636    let t = it
637        .specs
638        .get("thickness")
639        .and_then(Value::as_f64)
640        .filter(|t| *t > 0.0);
641    let semi = it
642        .specs
643        .get("diameter")
644        .and_then(semi_of)
645        .ok_or("no diameter (diameter)")?;
646    let material = it
647        .specs
648        .get("material")
649        .and_then(Value::as_str)
650        .unwrap_or("")
651        .to_string();
652    // 四角い品([幅, 高さ])は矩形の開口、semi は対角の半分(描く大きさ)
653    let rect = match it.specs.get("diameter") {
654        Some(Value::Array(a)) if a.len() == 2 => match (a[0].as_f64(), a[1].as_f64()) {
655            (Some(w), Some(h)) if w > 0.0 && h > 0.0 => Some((w / 2.0, h / 2.0)),
656            _ => None,
657        },
658        _ => None,
659    };
660    let semi = rect.map_or(semi, |(hx, hy)| hx.hypot(hy));
661    let ap = rect.map(|(hx, hy)| json!({ "type": "rect", "hx": hx, "hy": hy }));
662    let surf = |mut v: Value| {
663        if let Some(a) = &ap {
664            v["aperture"] = a.clone();
665        }
666        v
667    };
668    let block = if it.kind == Some(ItemKind::Mirror) {
669        surf(json!({ "type": "mirror", "semi": semi }))
670    } else {
671        let t = t.ok_or("no thickness (thickness)")?;
672        let (glass, cat, sub) = material_glass(&material);
673        if sub {
674            it.notes.push(if material.is_empty() {
675                "no substrate glass is given, so blocks use N-BK7 instead".to_string()
676            } else {
677                format!(
678                    "the glass of substrate \"{material}\" is unknown, so blocks use N-BK7 instead"
679                )
680            });
681        }
682        if !it.glass_catalogs.iter().any(|c| c == cat) {
683            it.glass_catalogs.push(cat.to_string());
684        }
685        json!({
686            "type": "lens",
687            "source": { "surfaces": [
688                surf(json!({ "t": t, "glass": glass, "semi": semi })),
689                surf(json!({ "semi": semi })),
690            ] },
691        })
692    };
693    let blocks = vec![serde_json::from_value(block).map_err(|e| format!("blocks: {e}"))?];
694    let mut frame_spec = None;
695    if let Some(f) = frame {
696        f.validate().map_err(|e| format!("mount: {e}"))?;
697        if f.bores.is_empty() {
698            return Err("mount: no bores (bores)".into());
699        }
700        let clear = f
701            .bores
702            .iter()
703            .map(|b| b.diameter)
704            .fold(f64::INFINITY, f64::min);
705        it.specs
706            .entry("clear_aperture".to_string())
707            .or_insert_with(|| json!(round6(clear)));
708        if let (Some(h), Some(t)) = (f.holds, t) {
709            let len = if f.length > 0.0 {
710                f.length
711            } else {
712                f.bores.iter().map(|b| b.z1).fold(0.0, f64::max)
713            };
714            if h.seat_z < 0.0 || h.seat_z + t > len + 1e-6 {
715                it.notes.push(format!(
716                    "the glass ({} to {} mm) sticks out of the mount length {len} mm",
717                    h.seat_z,
718                    h.seat_z + t
719                ));
720            }
721        }
722        if from == FillFrom::Page {
723            it.notes
724                .push("the seat in the mount isn't in the spec table, so the glass is placed at the middle of the mount".into());
725        }
726        it.notes.push(format!(
727            "split the mount from {what}: length {} mm, outer diameter {} mm, smallest inner diameter {} mm",
728            f.length,
729            f.outer_diameter,
730            round6(clear),
731            what = from.text(),
732        ));
733        frame_spec = Some(f);
734    }
735    let thick = item.missing().iter().any(|m| m == "thickness");
736    let dia = item.missing().iter().any(|m| m != "thickness");
737    let what = match (thick, dia) {
738        (true, true) => "the thickness and diameter",
739        (true, false) => "the thickness",
740        _ => "the diameter",
741    };
742    it.notes.push(format!(
743        "filled {what} from {e} ({checked})",
744        e = from.text()
745    ));
746    if from != FillFrom::Manual && !it.url.is_empty() {
747        it.source = it.url.clone();
748    }
749    if !checked.is_empty() {
750        it.checked = checked.to_string();
751    }
752    if it.description.is_empty() {
753        let d = match it.specs.get("diameter") {
754            Some(Value::Array(a)) => a
755                .iter()
756                .map(|x| x.to_string())
757                .collect::<Vec<_>>()
758                .join(" × "),
759            Some(x) => x.to_string(),
760            None => "—".into(),
761        };
762        it.description = format!(
763            "{}{}diameter {d} mm, thickness {} mm",
764            it.title,
765            if it.title.is_empty() { "" } else { ", " },
766            t.map_or("—".into(), |x| format!("{x}")),
767        );
768    }
769    it.body = lensbench_project::ItemBody::Optic {
770        blocks,
771        frame: frame_spec.map(|spec| lensbench_project::Frame {
772            spec,
773            reversed: false,
774        }),
775    };
776    Ok(it)
777}
778
779/// UNIX 時刻(秒)の日付(YYYY-MM-DD、UTC)
780pub fn date_of_unix(secs: u64) -> String {
781    // Howard Hinnant の civil_from_days
782    let z = (secs / 86400) as i64 + 719468;
783    let era = z.div_euclid(146097);
784    let doe = z - era * 146097;
785    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
786    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
787    let mp = (5 * doy + 2) / 153;
788    let d = doy - (153 * mp + 2) / 5 + 1;
789    let m = if mp < 10 { mp + 3 } else { mp - 9 };
790    let y = yoe + era * 400 + i64::from(m <= 2);
791    format!("{y:04}-{m:02}-{d:02}")
792}
793
794#[cfg(test)]
795mod tests {
796    use super::*;
797
798    #[test]
799    fn page_reads_thickness_and_diameter() {
800        // 欄と値が別の行(ブラウザの innerText の表)
801        let t = "Physical & Mechanical Properties\nDiameter (mm):\n25.00 +0.00/-0.10\nThickness (mm):\n3.00 ±0.10\nMounted Thickness (mm):\n5.00\nClear Aperture CA (mm):\n22.00\n";
802        let r = read_page(t);
803        assert_eq!(r.thickness, Some(3.0));
804        assert_eq!(r.diameter, Some(json!(25.0)));
805        // 同じ行(`欄: 値`・タブ)とインチ
806        let r = read_page("Thickness (inches):\t0.25\nDiameter (mm): 12.5");
807        assert_eq!(r.thickness, Some(6.35));
808        assert_eq!(r.diameter, Some(json!(12.5)));
809        // 単位の無い欄: 数の直後の in だけインチ(including などの語は mm のまま)
810        assert_eq!(
811            read_page("Thickness: 3.0 including AR coating").thickness,
812            Some(3.0)
813        );
814        assert_eq!(read_page("Thickness: 0.25 in").thickness, Some(6.35));
815        assert_eq!(read_page("Thickness: 0.25in").thickness, Some(6.35));
816        // 四角の寸法
817        let r = read_page("Dimensions (mm):\n25.0 x 35.0\nThickness (mm): 1.1");
818        assert_eq!(r.diameter, Some(json!([25.0, 35.0])));
819        assert_eq!(r.thickness, Some(1.1));
820    }
821
822    fn frame(len: f64, od: f64, bore: f64) -> lensbench_project::MechSpec {
823        lensbench_project::MechSpec {
824            bores: vec![lensbench_project::BoreSpec {
825                z0: 0.0,
826                z1: len,
827                diameter: bore,
828            }],
829            length: len,
830            outer_diameter: od,
831            holds: Some(lensbench_project::HoldSpec {
832                diameter: bore,
833                seat_z: 0.5,
834                max_diameter: 0.0,
835            }),
836            ..Default::default()
837        }
838    }
839
840    /// STEP で分けた寸法と仕様表の値の突き合わせ(Edmund の枠付きフィルタの形)
841    #[test]
842    fn spec_check_compares_glass_and_frame() {
843        let r = read_page("Diameter (mm):\n25.00\nSubstrate Thickness (mm):\n2.00\nMount Thickness (mm):\n3.50\nClear Aperture CA (mm):\n21.00\n");
844        let s = SpecValues::of(&serde_json::Map::new(), Some(&r));
845        let f = frame(3.5, 24.99, 21.209);
846        let c = spec_check(Some(2.0), Some(23.9), Some(&f), false, &s);
847        let keys: Vec<_> = c.iter().map(|c| (c.key, c.ok())).collect();
848        // 径 25 は枠の外径 24.99 と合い、枠の外径の欄が無いので枠の値として比べる
849        assert_eq!(
850            keys,
851            [
852                ("thickness", true),
853                ("mount_thickness", true),
854                ("mount_diameter", true),
855                ("clear_aperture", true),
856            ]
857        );
858        assert_eq!(c[2].spec_key, "diameter");
859        // 有効径が枠の穴より大きいのは食い違い
860        let big = SpecValues {
861            clear_aperture: Some(22.0),
862            ..s
863        };
864        let c = spec_check(Some(2.0), Some(23.9), Some(&f), false, &big);
865        assert!(!c[3].ok());
866        assert!(
867            c[3].note()
868                .contains("clear aperture: STEP 21.209 mm, spec table 22 mm"),
869            "{}",
870            c[3].note()
871        );
872        // 品の specs の値も使う(読んだページが先)
873        let mut m = serde_json::Map::new();
874        m.insert("thickness".into(), json!(1.5));
875        m.insert("clear_aperture".into(), json!(21.2));
876        let s2 = SpecValues::of(&m, None);
877        assert_eq!((s2.thickness, s2.clear_aperture), (Some(1.5), Some(21.2)));
878        let c = spec_check(Some(2.0), None, Some(&f), false, &s2);
879        assert_eq!(
880            c.iter()
881                .filter(|c| !c.ok())
882                .map(|c| c.key)
883                .collect::<Vec<_>>(),
884            ["thickness"]
885        );
886        assert_eq!(SpecValues::from_value(&s.to_value()), s);
887    }
888
889    /// ガラスと枠が 1 つの立体(Thorlabs のマウント付きフィルタの形): 仕様の厚さ・径は枠の値、
890    /// ガラスの径は見えている径なので比べない
891    #[test]
892    fn spec_check_merged_and_glass_diameter() {
893        let f = frame(6.3, 25.4, 21.0);
894        let s = SpecValues {
895            thickness: Some(6.3),
896            diameter: Some(25.4),
897            clear_aperture: Some(21.0),
898            ..Default::default()
899        };
900        let c = spec_check(Some(5.3), Some(21.0), Some(&f), true, &s);
901        assert_eq!(
902            c.iter()
903                .map(|c| (c.key, c.spec_key, c.ok()))
904                .collect::<Vec<_>>(),
905            [
906                ("mount_thickness", "thickness", true),
907                ("mount_diameter", "diameter", true),
908                ("clear_aperture", "clear_aperture", true),
909            ]
910        );
911        // 仕様の径が枠の値なら、ガラスの径は補えない
912        assert_eq!(spec_glass_diameter(21.0, &f, &s), None);
913        // ガラスの径の欄があれば補う
914        let s = SpecValues {
915            diameter: Some(22.0),
916            mount_diameter: Some(25.4),
917            ..s
918        };
919        assert_eq!(spec_glass_diameter(21.0, &f, &s), Some(22.0));
920        assert_eq!(
921            spec_glass_diameter(
922                21.0,
923                &f,
924                &SpecValues {
925                    diameter: Some(26.0),
926                    ..s
927                }
928            ),
929            None
930        );
931        // 枠の無い品は厚さ・径だけ
932        let c = spec_check(Some(2.0), Some(25.0), None, false, &s);
933        assert_eq!(
934            c.iter().map(|c| c.key).collect::<Vec<_>>(),
935            ["thickness", "diameter"]
936        );
937    }
938
939    /// 枠付きの品: 仕様表の枠の厚さ・外径・有効径から簡単な枠(ガラスは中央)
940    #[test]
941    fn page_frame_from_mount_fields() {
942        let t = "Diameter (mm):\n25.00\nSubstrate Thickness (mm):\n2.00\nMount Thickness (mm):\n3.50\nClear Aperture CA (mm):\n21.00\n";
943        let r = read_page(t);
944        assert_eq!(r.thickness, Some(2.0));
945        assert_eq!(
946            (r.mount_thickness, r.mount_diameter, r.clear_aperture),
947            (Some(3.5), None, Some(21.0))
948        );
949        let f = page_frame(&r, r.thickness, Some(23.9)).unwrap();
950        assert_eq!(f.length, 3.5);
951        assert_eq!(f.outer_diameter, 25.0);
952        assert_eq!(f.bores.len(), 1);
953        assert_eq!((f.bores[0].z1, f.bores[0].diameter), (3.5, 21.0));
954        let h = f.holds.unwrap();
955        assert_eq!((h.seat_z, h.diameter), (0.75, 23.9));
956        // 有効径の「90%」は寸法でない
957        assert_eq!(read_page("Clear Aperture (%): 90%").clear_aperture, None);
958        assert!(page_frame(&read_page("Mount Thickness (mm): 3.5"), None, None).is_none());
959        // 品に枠を入れる
960        let it = incomplete("filter", &["thickness"], json!({ "diameter": 25.0 }));
961        let c = complete(&it, Some(2.0), None, Some(f), FillFrom::Page, "").unwrap();
962        assert_eq!(c.frame().unwrap().spec.length, 3.5);
963        assert_eq!(c.specs["clear_aperture"], json!(21.0));
964        assert!(
965            c.notes.iter().any(|n| n.contains("middle of the mount")),
966            "{:?}",
967            c.notes
968        );
969        // はみ出すガラスは注記
970        let c = complete(
971            &it,
972            Some(4.0),
973            None,
974            page_frame(&r, None, None),
975            FillFrom::Page,
976            "",
977        )
978        .unwrap();
979        assert!(
980            c.notes.iter().any(|n| n.contains("sticks out")),
981            "{:?}",
982            c.notes
983        );
984    }
985
986    #[test]
987    fn page_without_values_does_not_stop() {
988        let r = read_page("");
989        assert_eq!(r, PageRead::default());
990        let r = read_page("Just a moment...\nVerify you are human\nThickness\n");
991        assert!(r.thickness.is_none() && r.diameter.is_none());
992        // 公称値が 2 つ並ぶ欄は決めない(見つけた欄としては返す)
993        let r = read_page("Substrate Thickness (mm):\n2.00 & 3.00\n");
994        assert!(r.thickness.is_none());
995        assert_eq!(r.found.len(), 1);
996        assert!(r.found[0].value.is_none());
997        // 大きなページ(数 MB)でも返る
998        let big = "lorem ipsum dolor\n".repeat(400_000) + "Thickness (mm): 2.0\n";
999        let r = read_page(&big);
1000        assert!(r.thickness.is_none() || r.thickness == Some(2.0));
1001    }
1002
1003    #[test]
1004    fn center_thickness_is_second_choice() {
1005        let r = read_page("Center Thickness CT (mm): 4.0\nThickness (mm): 3.0\n");
1006        assert_eq!(r.thickness, Some(3.0));
1007        let r = read_page("Center Thickness CT (mm): 4.0\n");
1008        assert_eq!(r.thickness, Some(4.0));
1009    }
1010
1011    fn incomplete(kind: &str, missing: &[&str], specs: Value) -> UserItem {
1012        serde_json::from_value(json!({
1013            "kind": kind, "url": "https://example.com/p/1", "title": "Filter 1",
1014            "missing": missing, "specs": specs,
1015        }))
1016        .unwrap()
1017    }
1018
1019    #[test]
1020    fn complete_builds_blocks() {
1021        let it = incomplete("filter", &["thickness"], json!({ "diameter": 25.0 }));
1022        assert!(it.is_incomplete());
1023        assert!(complete(&it, None, None, None, FillFrom::Page, "2026-11-10").is_err());
1024        let c = complete(&it, Some(3.0), None, None, FillFrom::Page, "2026-11-10").unwrap();
1025        assert!(!c.is_incomplete() && c.missing().is_empty());
1026        assert_eq!(c.blocks().len(), 1);
1027        assert_eq!(c.specs["thickness"], json!(3.0));
1028        assert_eq!(c.glass_catalogs, vec!["SCHOTT"]);
1029        assert_eq!(c.source, "https://example.com/p/1");
1030        assert_eq!(c.checked, "2026-11-10");
1031        assert!(c.notes.iter().any(|n| n.contains("use N-BK7 instead")));
1032        let b = serde_json::to_value(&c.blocks()[0]).unwrap();
1033        assert_eq!(b["type"], "lens");
1034        // 鏡は平面鏡、径だけ
1035        let m = incomplete(
1036            "mirror",
1037            &["diameter"],
1038            json!({ "material": "Fused Silica" }),
1039        );
1040        let c = complete(
1041            &m,
1042            None,
1043            Some(json!(25.4)),
1044            None,
1045            FillFrom::Step,
1046            "2026-11-10",
1047        )
1048        .unwrap();
1049        let b = serde_json::to_value(&c.blocks()[0]).unwrap();
1050        assert_eq!(b["type"], "mirror");
1051        assert_eq!(b["semi"], json!(12.7));
1052        // 基板の分かる品
1053        let w = incomplete(
1054            "polarizer",
1055            &["diameter"],
1056            json!({ "thickness": 2, "material": "Fused Silica (Corning 7980)" }),
1057        );
1058        let c = complete(
1059            &w,
1060            None,
1061            Some(json!([10.0, 20.0])),
1062            None,
1063            FillFrom::Manual,
1064            "",
1065        )
1066        .unwrap();
1067        assert_eq!(c.glass_catalogs, vec!["MISC"]);
1068        // 四角い品は両面に矩形の開口、semi は対角の半分
1069        let b = serde_json::to_value(&c.blocks()[0]).unwrap();
1070        for q in b["source"]["surfaces"].as_array().unwrap() {
1071            assert_eq!(q["aperture"]["type"], "rect", "{q}");
1072            assert_eq!(q["aperture"]["hx"], json!(5.0));
1073            assert_eq!(q["aperture"]["hy"], json!(10.0));
1074            assert!((q["semi"].as_f64().unwrap() - 125f64.sqrt()).abs() < 1e-12);
1075        }
1076        let c = complete(
1077            &m,
1078            None,
1079            Some(json!([10.0, 20.0])),
1080            None,
1081            FillFrom::Manual,
1082            "",
1083        )
1084        .unwrap();
1085        let b = serde_json::to_value(&c.blocks()[0]).unwrap();
1086        assert_eq!(b["aperture"]["hx"], json!(5.0));
1087        assert_eq!(b["aperture"]["hy"], json!(10.0));
1088        assert!(c.notes.iter().all(|n| !n.contains("N-BK7 instead")));
1089    }
1090
1091    #[test]
1092    fn dates() {
1093        assert_eq!(date_of_unix(0), "1970-01-01");
1094        assert_eq!(date_of_unix(1_794_268_800), "2026-11-10");
1095    }
1096}