1use std::path::{Path, PathBuf};
5
6use lensbench_core::catalog::LensCatalog;
7use lensbench_core::error::code;
8use lensbench_core::{Error, System};
9use lensbench_formats::zmx;
10
11fn bad_arg(m: String) -> Error {
13 Error::Invalid(m).with_code(code::BAD_ARGUMENT)
14}
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum FileKind {
19 Zmx,
21 Project,
23 SystemFile,
25}
26
27impl FileKind {
28 pub fn of(path: &Path) -> FileKind {
30 if !is_json(path) {
31 FileKind::Zmx
32 } else if crate::sysfile::is_system_file(path) {
33 FileKind::SystemFile
34 } else {
35 FileKind::Project
36 }
37 }
38}
39
40pub fn is_json(path: &Path) -> bool {
42 path.extension()
43 .is_some_and(|x| x.eq_ignore_ascii_case("json"))
44}
45
46#[derive(Clone, Default)]
48pub struct OpenSpec<'a> {
49 pub glass_dirs: &'a [PathBuf],
51 pub lens_catalogs: &'a [PathBuf],
53 pub cfg: usize,
55 pub state: Option<&'a str>,
57 pub split_path: Option<&'a str>,
59 pub wavelengths: Option<Vec<f64>>,
61 pub names: ArgNames,
63 pub step_files: Option<crate::StepLookup<'a>>,
65}
66
67impl OpenSpec<'_> {
68 fn cache_scope(&self) -> String {
70 format!("{:?}|{:?}", self.glass_dirs, self.lens_catalogs)
71 }
72}
73
74impl std::fmt::Debug for OpenSpec<'_> {
75 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76 f.debug_struct("OpenSpec")
77 .field("glass_dirs", &self.glass_dirs)
78 .field("lens_catalogs", &self.lens_catalogs)
79 .field("cfg", &self.cfg)
80 .field("state", &self.state)
81 .field("split_path", &self.split_path)
82 .field("wavelengths", &self.wavelengths)
83 .field("names", &self.names)
84 .field("step_files", &self.step_files.is_some())
85 .finish()
86 }
87}
88
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
91pub struct ArgNames {
92 pub cfg: &'static str,
93 pub state: &'static str,
94 pub split_path: &'static str,
95}
96
97impl ArgNames {
98 pub const CLI: ArgNames = ArgNames {
100 cfg: "--cfg",
101 state: "--state",
102 split_path: "--beam-path",
103 };
104 pub const SERVE: ArgNames = ArgNames {
106 cfg: "cfg",
107 state: "state",
108 split_path: "beam_path",
109 };
110 pub const PYTHON: ArgNames = ArgNames {
112 cfg: "cfg",
113 state: "state",
114 split_path: "beam_path",
115 };
116}
117
118impl Default for ArgNames {
120 fn default() -> Self {
121 ArgNames::CLI
122 }
123}
124
125#[derive(Clone, Debug)]
127pub struct Opened {
128 pub system: System,
129 pub warnings: Vec<String>,
131 pub coatings: Vec<PathBuf>,
133 pub blocks: Vec<crate::BlockSpans>,
135 pub faces: Vec<Option<crate::FaceId>>,
138}
139
140pub fn open(path: &Path, o: &OpenSpec) -> Result<Opened, Error> {
143 if o.cfg == 0 {
144 return Err(bad_arg(format!("{} must be 1 or more", o.names.cfg)));
145 }
146 Source::read(path)?.open(o)
147}
148
149pub fn open_with(
151 path: &Path,
152 o: &OpenSpec,
153 step_files: Option<crate::StepLookup>,
154) -> Result<Opened, Error> {
155 open(
156 path,
157 &OpenSpec {
158 step_files,
159 ..o.clone()
160 },
161 )
162}
163
164#[derive(Clone, Debug)]
167pub enum Source {
168 Zmx { path: PathBuf, text: String },
170 SystemFile { path: PathBuf, text: String },
172 Project {
173 path: PathBuf,
174 text: String,
176 project: Box<crate::Project>,
177 cache: std::sync::Arc<crate::SourceCache>,
179 },
180}
181
182impl Source {
183 pub fn read(path: &Path) -> Result<Source, Error> {
186 if lensbench_core::vfs::is_dir(path) {
187 return Err(
188 Error::Io(format!("{}: a folder (give a system file)", path.display()))
189 .with_code(code::IS_FOLDER),
190 );
191 }
192 if !lensbench_core::vfs::is_file(path) {
193 return Err(Error::Io(format!("{}: no such file", path.display()))
194 .with_code(code::FILE_NOT_FOUND));
195 }
196 let path_buf = path.to_path_buf();
197 if !is_json(path) {
198 let text = lensbench_core::glass::read_text(path)
199 .map_err(|e| Error::Io(format!("{}: {e}", path.display())))?;
200 return Ok(Source::Zmx {
201 path: path_buf,
202 text,
203 });
204 }
205 let txt = lensbench_core::vfs::read_to_string(path)
206 .map_err(|e| Error::Io(format!("{}: {e}", path.display())))?;
207 if crate::sysfile::is_system_json(&txt) {
208 return Ok(Source::SystemFile {
209 path: path_buf,
210 text: txt,
211 });
212 }
213 let project = crate::Project::from_json(&txt).map_err(|e| e.at(path.display()))?;
214 Ok(Source::Project {
215 path: path_buf,
216 text: txt,
217 project: Box::new(project),
218 cache: Default::default(),
219 })
220 }
221
222 pub fn kind(&self) -> FileKind {
224 match self {
225 Source::Zmx { .. } => FileKind::Zmx,
226 Source::SystemFile { .. } => FileKind::SystemFile,
227 Source::Project { .. } => FileKind::Project,
228 }
229 }
230
231 pub fn path(&self) -> &Path {
233 match self {
234 Source::Zmx { path: p, .. }
235 | Source::SystemFile { path: p, .. }
236 | Source::Project { path: p, .. } => p,
237 }
238 }
239
240 pub fn zmx_configs(
242 &self,
243 opt: &zmx::LoadOptions,
244 cfgs: &[usize],
245 ) -> Result<Vec<System>, Error> {
246 match self {
247 Source::Zmx { path, text } => zmx::load_configs_text(text, path, opt, cfgs),
248 _ => Err(bad_arg("configurations are only for .zmx".into())),
249 }
250 }
251
252 pub fn configurations(&self) -> Result<usize, Error> {
254 match self {
255 Source::Zmx { text, .. } => Ok(zmx::parse_text(text)?.configurations()),
256 _ => Ok(1),
257 }
258 }
259
260 pub fn project(&self) -> Option<&crate::Project> {
262 match self {
263 Source::Project { project, .. } => Some(project),
264 _ => None,
265 }
266 }
267
268 pub fn project_text(&self) -> Option<&str> {
270 match self {
271 Source::Project { text, .. } => Some(text),
272 _ => None,
273 }
274 }
275
276 pub fn states(&self) -> Vec<String> {
278 self.project()
279 .map(|p| p.state_names().iter().map(|s| s.to_string()).collect())
280 .unwrap_or_default()
281 }
282
283 pub fn beams(&self) -> Vec<String> {
285 self.project()
286 .map(|p| p.beam_names().iter().map(|s| s.to_string()).collect())
287 .unwrap_or_default()
288 }
289
290 fn project_in(&self, state: Option<&str>) -> Result<Option<crate::Project>, Error> {
292 let Some(p) = self.project() else {
293 return Ok(None);
294 };
295 Ok(Some(match state {
296 Some(n) => p.with_state(n)?,
297 None => p.clone(),
298 }))
299 }
300
301 fn env<'c>(&self, o: &OpenSpec<'c>, cat: Option<crate::CatalogLookup<'c>>) -> crate::Env<'c> {
303 crate::Env {
304 base: self
305 .path()
306 .parent()
307 .map(|p| p.to_path_buf())
308 .unwrap_or_default(),
309 glass_dirs: o.glass_dirs.to_vec(),
310 catalog: cat,
311 step_files: o.step_files,
312 }
313 }
314
315 pub fn paths(&self, o: &OpenSpec) -> Result<Vec<String>, Error> {
317 let Some(p) = self.project_in(o.state)? else {
318 return Ok(Vec::new());
319 };
320 let cat = LensCatalog::load_registered(o.lens_catalogs)?;
321 let look = |v: &str, q: &str| cat.zmx(v, q);
322 let cache = match self {
323 Source::Project { cache, .. } => cache.clone(),
324 _ => Default::default(),
325 };
326 cache.scope(&o.cache_scope());
327 crate::paths_cached(&p, &self.env(o, Some(&look)), &cache)
328 }
329
330 pub fn open(&self, o: &OpenSpec) -> Result<Opened, Error> {
332 let ArgNames {
333 cfg,
334 state,
335 split_path: split,
336 } = o.names;
337 if o.cfg == 0 {
338 return Err(bad_arg(format!("{cfg} must be 1 or more")));
339 }
340 match self {
341 Source::SystemFile { path, text } => {
342 if o.cfg != 1 || o.state.is_some() || o.split_path.is_some() {
343 return Err(bad_arg(format!(
344 "{cfg}, {state} and {split} can't be used with a system file"
345 )));
346 }
347 if o.wavelengths.is_some() {
348 return Err(bad_arg(
349 "wavelengths is only for .zmx and project files".into(),
350 ));
351 }
352 let (system, m, warnings) =
353 crate::sysfile::load_text_with(path, text, o.glass_dirs)?;
354 Ok(Opened {
355 system,
356 warnings,
357 coatings: m.coatings,
358 blocks: Vec::new(),
359 faces: Vec::new(),
360 })
361 }
362 Source::Project {
363 path,
364 project,
365 cache,
366 ..
367 } => {
368 if o.cfg != 1 {
369 return Err(bad_arg(format!(
370 "choose the state with {state}, not {cfg}, in a project file"
371 )));
372 }
373 let at = |e: Error| e.at(path.display());
374 let mut p = match o.state {
375 Some(n) => project
376 .with_state_and_path(n, o.split_path.is_some())
377 .map_err(at)?,
378 None => (**project).clone(),
379 };
380 if let Some(w) = &o.wavelengths {
382 if p.primary == 0 || p.primary > w.len() {
383 let (pw, nw) = (p.primary, w.len());
384 return Err(at(Error::Invalid(format!(
385 "primary wavelength {pw} (there are {nw} wavelengths)"
386 ))));
387 }
388 p.wavelengths = w
389 .iter()
390 .map(|&um| crate::model::Wave { um, weight: 1.0 })
391 .collect();
392 }
393 let cat = LensCatalog::load_registered(o.lens_catalogs)?;
394 let look = |v: &str, q: &str| cat.zmx(v, q);
395 cache.scope(&o.cache_scope());
396 let x = crate::expand(
397 &p,
398 &self.env(o, Some(&look)),
399 &crate::ExpandOpts {
400 path: o.split_path,
401 cache: Some(cache),
402 ..Default::default()
403 },
404 )
405 .map_err(|e| at(e.into()))?;
406 let blocks = x.block_spans();
407 let faces = x.map.into_iter().map(|o| o.face).collect();
408 Ok(Opened {
409 system: x.system,
410 warnings: x.notes.into_iter().map(String::from).collect(),
411 coatings: Vec::new(),
412 blocks,
413 faces,
414 })
415 }
416 Source::Zmx { path, text } => {
417 if o.state.is_some() {
418 return Err(bad_arg(format!(
419 "{state} is only for project files (.json) (.zmx uses {cfg})"
420 )));
421 }
422 if o.split_path.is_some() {
423 return Err(bad_arg(format!(
424 "{split} is only for project files (.json)"
425 )));
426 }
427 let opt = zmx::LoadOptions {
428 cfg: o.cfg,
429 catalog_dirs: o.glass_dirs.to_vec(),
430 wavelengths: o.wavelengths.clone(),
431 ..Default::default()
432 };
433 Ok(Opened {
434 system: zmx::load_text_with(text, path, &opt)?,
435 warnings: Vec::new(),
436 coatings: Vec::new(),
437 blocks: Vec::new(),
438 faces: Vec::new(),
439 })
440 }
441 }
442 }
443}
444
445#[cfg(test)]
446mod tests {
447 use super::*;
448
449 #[test]
450 fn missing_file_is_io() {
451 let o = OpenSpec {
452 cfg: 1,
453 ..Default::default()
454 };
455 for f in ["nosuch.zmx", "nosuch.json", "nosuch.lbsys.json"] {
456 let e = open(Path::new(f), &o).unwrap_err();
457 assert_eq!(e.kind(), "io", "{f}: {e}");
458 assert_eq!(e.code(), code::FILE_NOT_FOUND, "{f}: {e}");
459 }
460 }
461
462 #[test]
463 fn bad_arguments_are_invalid() {
464 let o = OpenSpec {
465 cfg: 0,
466 ..Default::default()
467 };
468 let e = open(Path::new("x.zmx"), &o).unwrap_err();
469 assert_eq!((e.kind(), e.code()), ("invalid", code::BAD_ARGUMENT));
470 }
471
472 #[test]
473 fn file_kinds() {
474 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
475 let prj = root.join("examples/projects/P10_catalog_four.json");
476 assert_eq!(FileKind::of(&prj), FileKind::Project);
477 assert_eq!(
478 FileKind::of(&root.join("tests/refs/A0/system.zmx")),
479 FileKind::Zmx
480 );
481 let a0 = lensbench_formats::zmx::load_with(
482 &root.join("tests/refs/A0/system.zmx"),
483 &lensbench_formats::zmx::LoadOptions {
484 cfg: 1,
485 catalog_dirs: vec![root.join("tests/glass")],
486 ..Default::default()
487 },
488 )
489 .unwrap();
490 let s = crate::sysfile::to_string(&a0, &[]).unwrap();
491 let dir = std::env::temp_dir().join(format!("lb_open_kind_{}", std::process::id()));
492 std::fs::create_dir_all(&dir).unwrap();
493 let f = dir.join("sys.JSON");
494 std::fs::write(&f, s).unwrap();
495 assert_eq!(FileKind::of(&f), FileKind::SystemFile);
496 let _ = std::fs::remove_dir_all(&dir);
497 }
498
499 #[test]
501 fn project_with_replaced_wavelengths() {
502 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
503 let glass = [root.join("tests/glass")];
504 let src = Source::read(&root.join("examples/projects/P16_twyman_green.json")).unwrap();
505 let o = OpenSpec {
506 glass_dirs: &glass,
507 cfg: 1,
508 state: Some("reference arm"),
509 wavelengths: Some(vec![0.84, 0.83, 0.85]),
510 ..Default::default()
511 };
512 let s = src.open(&o).unwrap().system;
513 assert_eq!(s.wavelengths, vec![0.84, 0.83, 0.85]);
514 assert_eq!(s.weights, vec![1.0; 3]);
515 assert_eq!(s.primary, 0);
516 let plain = src
517 .open(&OpenSpec {
518 wavelengths: None,
519 ..o.clone()
520 })
521 .unwrap()
522 .system;
523 assert_eq!(s.surfaces.len(), plain.surfaces.len());
524 let e = src
525 .open(&OpenSpec {
526 wavelengths: Some(Vec::new()),
527 ..o
528 })
529 .unwrap_err();
530 assert!(e.to_string().contains("primary wavelength 1"), "{e}");
531 }
532
533 #[test]
535 fn source_reads_the_project_once() {
536 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
537 let glass = [root.join("tests/glass")];
538 for f in ["P16_twyman_green.json", "P6_states_focus_group.json"] {
539 let path = root.join("examples/projects").join(f);
540 let src = Source::read(&path).unwrap();
541 assert_eq!(src.kind(), FileKind::Project);
542 assert!(src.project_text().is_some());
543 let names = src.states();
544 assert_eq!(names, src.project().unwrap().state_names());
545 let mut states: Vec<Option<&str>> = vec![None];
546 states.extend(names.iter().map(|s| Some(s.as_str())));
547 for st in states {
548 let o = OpenSpec {
549 glass_dirs: &glass,
550 cfg: 1,
551 state: st,
552 ..Default::default()
553 };
554 let direct = open(&path, &o).unwrap().system;
555 let s = src.open(&o).unwrap().system;
556 assert_eq!(format!("{s:?}"), format!("{direct:?}"), "{f} {st:?}");
557 src.paths(&o).unwrap();
558 }
559 }
560 }
561
562 #[test]
564 fn codes_survive_open() {
565 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
566 let glass = [root.join("tests/glass")];
567 let p = root.join("examples/projects/P6_states_focus_group.json");
568 let o = OpenSpec {
569 glass_dirs: &glass,
570 cfg: 1,
571 state: Some("nosuch"),
572 ..Default::default()
573 };
574 let e = open(&p, &o).unwrap_err();
575 assert_eq!(
576 (e.kind(), e.code()),
577 ("invalid", code::STATE_NOT_FOUND),
578 "{e}"
579 );
580 let empty = std::env::temp_dir().join(format!("lb_open_code_{}", std::process::id()));
582 std::fs::create_dir_all(&empty).unwrap();
583 let src = std::fs::read_to_string(root.join("examples/projects/P5_triplet_blocks.json"))
584 .unwrap()
585 .replace("\"SCHOTT\"", "\"NOSUCHCAT\"")
586 .replace(
587 "../../tests/refs",
588 &root
589 .join("tests/refs")
590 .display()
591 .to_string()
592 .replace('\\', "/"),
593 );
594 let proj = empty.join("p.json");
595 std::fs::write(&proj, src).unwrap();
596 let dirs = [empty.clone()];
597 let o = OpenSpec {
598 glass_dirs: &dirs,
599 cfg: 1,
600 ..Default::default()
601 };
602 let e = open(&proj, &o).unwrap_err();
603 let _ = std::fs::remove_dir_all(&empty);
604 assert_eq!(e.code(), code::GLASS_NOT_FOUND, "{e}");
605 assert!(e.to_string().contains("--glass-dir"), "{e}");
606 }
607
608 #[test]
609 fn folder_is_io_with_its_own_message() {
610 let o = OpenSpec {
611 cfg: 1,
612 ..Default::default()
613 };
614 let e = open(Path::new("."), &o).unwrap_err();
615 assert_eq!((e.kind(), e.code()), ("io", code::IS_FOLDER));
616 assert!(e.message().unwrap_or_default().contains("a folder"), "{e}");
617 }
618}