1use lensbench_core::System;
21use serde_json::{Map, Value};
22use sha2::{Digest, Sha256};
23use std::path::{Path, PathBuf};
24
25pub const FORMAT: &str = "lensbench-system";
27pub const FORMAT_VERSION: u64 = 2;
29
30#[derive(Debug, Clone, Default, PartialEq)]
32pub struct Meta {
33 pub lensbench: String,
35 pub hash: String,
37 pub coatings: Vec<PathBuf>,
39}
40
41pub fn is_system_json(txt: &str) -> bool {
43 match serde_json::from_str::<Value>(txt) {
45 Ok(Value::Object(m)) => m.get("format").and_then(Value::as_str) == Some(FORMAT),
46 _ => false,
47 }
48}
49
50pub fn is_system_file(path: &Path) -> bool {
52 if !path
53 .extension()
54 .is_some_and(|x| x.eq_ignore_ascii_case("json"))
55 {
56 return false;
57 }
58 lensbench_core::vfs::read_to_string(path).is_ok_and(|t| is_system_json(&t))
59}
60
61pub(crate) fn to_json(v: ciborium::value::Value) -> lensbench_core::Result<Value> {
62 use ciborium::value::Value as C;
63 Ok(match v {
64 C::Null => Value::Null,
65 C::Bool(b) => Value::Bool(b),
66 C::Integer(i) => {
67 let i: i128 = i.into();
68 if let Ok(u) = u64::try_from(i) {
69 Value::from(u)
70 } else if let Ok(s) = i64::try_from(i) {
71 Value::from(s)
72 } else {
73 return Err(format!("integer {i} is too large").into());
74 }
75 }
76 C::Float(f) => {
77 if f.is_finite() {
78 Value::from(f)
79 } else {
80 let s = if f.is_nan() {
81 "nan"
82 } else if f > 0.0 {
83 "inf"
84 } else {
85 "-inf"
86 };
87 let mut m = Map::new();
88 m.insert("$f".into(), Value::from(s));
89 Value::Object(m)
90 }
91 }
92 C::Text(s) => Value::String(s),
93 C::Array(a) => Value::Array(a.into_iter().map(to_json).collect::<Result<_, _>>()?),
94 C::Map(m) => {
95 let mut o = Map::new();
96 for (k, v) in m {
97 let C::Text(k) = k else {
98 return Err(format!("a table key is not a string ({k:?})").into());
99 };
100 o.insert(k, to_json(v)?);
101 }
102 Value::Object(o)
103 }
104 C::Tag(_, v) => to_json(*v)?,
105 C::Bytes(_) => return Err("bytes can't be written".into()),
106 _ => return Err("a value that can't be written".into()),
107 })
108}
109
110pub(crate) fn from_json(v: Value) -> lensbench_core::Result<ciborium::value::Value> {
111 use ciborium::value::Value as C;
112 Ok(match v {
113 Value::Null => C::Null,
114 Value::Bool(b) => C::Bool(b),
115 Value::Number(n) => {
116 if let Some(u) = n.as_u64() {
117 C::Integer(u.into())
118 } else if let Some(i) = n.as_i64() {
119 C::Integer(i.into())
120 } else {
121 C::Float(n.as_f64().ok_or("number")?)
122 }
123 }
124 Value::String(s) => C::Text(s),
125 Value::Array(a) => C::Array(a.into_iter().map(from_json).collect::<Result<_, _>>()?),
126 Value::Object(m) => {
127 if m.len() == 1 {
128 if let Some(Value::String(s)) = m.get("$f") {
129 return Ok(C::Float(match s.as_str() {
130 "inf" => f64::INFINITY,
131 "-inf" => f64::NEG_INFINITY,
132 "nan" => f64::NAN,
133 _ => return Err(format!("number {{\"$f\": {s:?}}}").into()),
134 }));
135 }
136 }
137 C::Map(
138 m.into_iter()
139 .map(|(k, v)| Ok((C::Text(k), from_json(v)?)))
140 .collect::<lensbench_core::Result<_>>()?,
141 )
142 }
143 })
144}
145
146pub(crate) fn internal_value(s: &System) -> lensbench_core::Result<Value> {
148 let c =
149 ciborium::value::Value::serialized(s).map_err(|e| format!("writing the system: {e}"))?;
150 let mut v = to_json(c)?;
151 if let Some(Value::Object(g)) = v.get_mut("glasses") {
152 let mut items: Vec<(String, Value)> = std::mem::take(g).into_iter().collect();
153 items.sort_by(|a, b| a.0.cmp(&b.0));
154 g.extend(items);
155 }
156 Ok(v)
157}
158
159fn system_value(s: &System) -> lensbench_core::Result<Value> {
161 let p = crate::sysfile_v2::write::prescription(s)?;
162 let c =
163 ciborium::value::Value::serialized(&p).map_err(|e| format!("writing the system: {e}"))?;
164 to_json(c)
165}
166
167pub fn catalog_files(s: &System) -> Vec<PathBuf> {
170 crate::sysfile_v2::catalogs::files(s)
171}
172
173fn canonical(v: &Value, out: &mut String) {
175 match v {
176 Value::Object(m) => {
177 let mut keys: Vec<&String> = m.keys().collect();
178 keys.sort();
179 out.push('{');
180 for (i, k) in keys.into_iter().enumerate() {
181 if i > 0 {
182 out.push(',');
183 }
184 out.push_str(&serde_json::to_string(k).expect("JSON"));
185 out.push(':');
186 canonical(&m[k], out);
187 }
188 out.push('}');
189 }
190 Value::Array(a) => {
191 out.push('[');
192 for (i, x) in a.iter().enumerate() {
193 if i > 0 {
194 out.push(',');
195 }
196 canonical(x, out);
197 }
198 out.push(']');
199 }
200 x => out.push_str(&serde_json::to_string(x).expect("JSON")),
201 }
202}
203
204pub fn hash_value(v: &Value) -> String {
205 let mut txt = String::new();
206 canonical(v, &mut txt);
207 let d = Sha256::digest(txt.as_bytes());
208 let hex: String = d.iter().map(|b| format!("{b:02x}")).collect();
209 format!("sha256:{hex}")
210}
211
212pub fn system_hash(s: &System) -> lensbench_core::Result<String> {
214 Ok(hash_value(&system_value(s)?))
215}
216
217pub fn to_string(s: &System, coatings: &[PathBuf]) -> lensbench_core::Result<String> {
219 let sv = system_value(s)?;
220 let hash = hash_value(&sv);
221 let mut o = Map::new();
222 o.insert("$schema".into(), Value::from(crate::schema::url("system")));
223 o.insert("format".into(), Value::from(FORMAT));
224 o.insert("format_version".into(), Value::from(FORMAT_VERSION));
225 o.insert("lensbench".into(), Value::from(lensbench_core::VERSION));
226 o.insert("hash".into(), Value::from(hash));
227 o.insert(
228 "coatings".into(),
229 Value::Array(
230 coatings
231 .iter()
232 .map(|p| Value::from(p.to_string_lossy().to_string()))
233 .collect(),
234 ),
235 );
236 o.insert("system".into(), sv);
237 Ok(crate::schema::to_text(&Value::Object(o)))
239}
240
241pub fn from_str(txt: &str) -> lensbench_core::Result<(System, Meta, Vec<String>)> {
244 from_str_with(txt, &[])
245}
246
247pub fn from_str_with(
250 txt: &str,
251 glass_dirs: &[PathBuf],
252) -> lensbench_core::Result<(System, Meta, Vec<String>)> {
253 let v: Value = serde_json::from_str(txt).map_err(|e| format!("system file: {e}"))?;
254 let Value::Object(mut o) = v else {
255 return Err("system file: not a JSON object".into());
256 };
257 if o.get("format").and_then(Value::as_str) != Some(FORMAT) {
258 return Err(format!("system file: format is not {FORMAT}").into());
259 }
260 let ver = o
261 .get("format_version")
262 .and_then(Value::as_u64)
263 .ok_or("system file: no format_version")?;
264 if ver > FORMAT_VERSION {
265 return Err(format!(
266 "system file: version {ver} can't be read (up to {FORMAT_VERSION}; update lensbench)"
267 )
268 .into());
269 }
270 if ver < FORMAT_VERSION {
271 return Err(format!(
272 "system file: version {ver} is no longer read (open and save it with lensbench 0.5 to make version {FORMAT_VERSION})"
273 )
274 .into());
275 }
276 let sv = o.remove("system").ok_or("system file: no system")?;
277 let mut warn = Vec::new();
278 let hash_now = hash_value(&sv);
279 let hash = o
280 .get("hash")
281 .and_then(Value::as_str)
282 .unwrap_or("")
283 .to_string();
284 let c = from_json(sv).map_err(|e| format!("system file: {e}"))?;
285 let p: crate::sysfile_v2::Prescription =
286 crate::lenient::decode(c, "system").map_err(|e| format!("system file: {e}"))?;
287 let dirs = lensbench_core::glass::catalog_dirs(glass_dirs);
288 let (mut g, notes) =
289 crate::sysfile_v2::catalogs::load(&p.catalogs, &dirs).map_err(|e| e.at("system file"))?;
290 warn.extend(notes);
291 let named = p.surfaces.iter().filter_map(|r| match &r.medium {
293 Some(crate::sysfile_v2::Medium::Glass(m)) if m.contains('@') => Some(m.as_str()),
294 _ => None,
295 });
296 lensbench_core::glass::resolve_qualified(&mut g, named, &dirs);
297 let sys = crate::sysfile_v2::read::system(p, std::sync::Arc::new(g))
298 .map_err(|e| format!("system file: {e}"))?;
299 check(&sys)?;
300 let hash_sys = system_hash(&sys)?;
302 if !hash.is_empty() && hash != hash_now && hash != hash_sys {
303 warn.push(format!(
304 "the hash of the system file doesn't match its content (edited after writing? recorded {hash}, now {hash_sys})"
305 ));
306 }
307 let coatings = match o.get("coatings") {
308 None | Some(Value::Null) => Vec::new(),
309 Some(Value::Array(a)) => a
310 .iter()
311 .map(|x| {
312 x.as_str()
313 .map(PathBuf::from)
314 .ok_or_else(|| "system file: coatings must be a list of strings".to_string())
315 })
316 .collect::<Result<_, _>>()?,
317 Some(_) => return Err("system file: coatings must be a list of strings".into()),
318 };
319 let meta = Meta {
320 lensbench: o
321 .get("lensbench")
322 .and_then(Value::as_str)
323 .unwrap_or("")
324 .to_string(),
325 hash: hash_sys,
326 coatings,
327 };
328 Ok((sys, meta, warn))
329}
330
331pub fn check(sys: &System) -> lensbench_core::Result<()> {
333 let nw = sys.wavelengths.len();
334 if nw == 0 || sys.weights.len() != nw || sys.primary >= nw {
335 return Err(
336 "system file: the numbers of wavelengths, weights and primary don't match".into(),
337 );
338 }
339 check_refs(sys)?;
340 Ok(sys.check().map_err(|e| format!("system file: {e}"))?)
341}
342
343pub(crate) fn check_refs(sys: &lensbench_core::Prescription) -> lensbench_core::Result<()> {
345 let ns = sys.surfaces.len();
346 for p in &sys.pickups {
347 if p.src >= ns || p.dst >= ns {
348 return Err(format!("system file: pickup surfaces ({} → {})", p.src, p.dst).into());
349 }
350 }
351 for q in &sys.solves {
352 if q.surf >= ns || q.kind.other_surface().is_some_and(|f| f >= ns) {
353 return Err(format!("system file: solve surface {}", q.surf).into());
354 }
355 if let lensbench_core::solves::SolveKind::MacroCurv { index: i }
356 | lensbench_core::solves::SolveKind::MacroThick { index: i } = q.kind
357 {
358 if i as usize >= sys.macros.len() {
359 return Err(format!("system file: no macro {i} for surface {}", q.surf).into());
360 }
361 }
362 }
363 for q in &sys.macro_parms {
364 if q.surf >= ns || q.id as usize >= sys.macros.len() {
365 return Err(format!("system file: macro solve (surface {})", q.surf).into());
366 }
367 }
368 for u in &sys.units {
369 if u.spans.iter().any(|s| s[0] > s[1] || s[1] >= ns) {
370 return Err(format!("system file: range of lens or group {}", u.name).into());
371 }
372 }
373 if sys.glrs >= ns {
374 return Err(format!(
375 "system file: global coordinate reference surface {}",
376 sys.glrs
377 )
378 .into());
379 }
380 Ok(())
381}
382
383pub fn save(path: &Path, s: &System, coatings: &[PathBuf]) -> lensbench_core::Result<()> {
385 let txt = to_string(s, coatings)?;
386 lensbench_core::vfs::write_atomic(path, txt)
387 .map_err(lensbench_core::Error::io_at(path.display()))
388}
389
390pub fn save_notes(s: &System) -> Vec<String> {
393 crate::sysfile_v2::catalogs::unverified(s)
394}
395
396pub fn load(path: &Path) -> lensbench_core::Result<(System, Meta, Vec<String>)> {
399 load_with(path, &[])
400}
401
402pub fn load_with(
404 path: &Path,
405 glass_dirs: &[PathBuf],
406) -> lensbench_core::Result<(System, Meta, Vec<String>)> {
407 let txt = lensbench_core::vfs::read_to_string(path)
408 .map_err(lensbench_core::Error::io_at(path.display()))?;
409 load_text_with(path, &txt, glass_dirs)
410}
411
412pub fn load_text_with(
414 path: &Path,
415 txt: &str,
416 glass_dirs: &[PathBuf],
417) -> lensbench_core::Result<(System, Meta, Vec<String>)> {
418 let base = path
420 .parent()
421 .filter(|p| !p.as_os_str().is_empty())
422 .unwrap_or(Path::new("."));
423 let mut dirs = glass_dirs.to_vec();
424 dirs.push(base.to_path_buf());
425 let (s, mut m, w) = from_str_with(txt, &dirs).map_err(|e| e.at(path.display()))?;
426 for c in m.coatings.iter_mut() {
427 if c.is_relative() {
428 *c = base.join(&*c);
429 }
430 }
431 Ok((s, m, w))
432}