1use super::*;
4use serde::{Deserialize, Serialize};
5
6#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
8pub struct BrowseReq {
9 pub glass_dirs: Vec<PathBuf>,
10 pub lens_catalogs: Vec<PathBuf>,
12}
13
14#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
17pub struct SearchReq {
18 pub glass_dirs: Vec<PathBuf>,
19 pub lens_catalogs: Vec<PathBuf>,
20 pub kinds: Vec<String>,
21 pub vendor: String,
22 pub text: String,
23 pub specs: Vec<String>,
24 pub fits: Option<f64>,
25}
26
27impl BrowseReq {
28 pub(super) fn parse(method: &str, p: &Value) -> Result<BrowseReq, RpcErr> {
30 let keys: &[&str] = match method {
31 "glasses" => &["glass_dirs"],
32 _ => &["glass_dirs", "lens_catalogs"],
33 };
34 known_keys(p, keys)?;
35 Ok(BrowseReq {
36 glass_dirs: str_list(&p["glass_dirs"], "glass_dirs")?,
37 lens_catalogs: str_list(&p["lens_catalogs"], "lens_catalogs")?,
38 })
39 }
40}
41
42impl SearchReq {
43 pub(super) fn parse(p: &Value) -> Result<SearchReq, RpcErr> {
45 known_keys(
46 p,
47 &[
48 "glass_dirs",
49 "lens_catalogs",
50 "kinds",
51 "vendor",
52 "text",
53 "specs",
54 "fits",
55 ],
56 )?;
57 let strs = |k: &str| -> Result<Vec<String>, RpcErr> {
58 Ok(str_list(&p[k], k)?
59 .into_iter()
60 .map(|x| x.to_string_lossy().into_owned())
61 .collect())
62 };
63 let r = SearchReq {
64 glass_dirs: str_list(&p["glass_dirs"], "glass_dirs")?,
65 lens_catalogs: str_list(&p["lens_catalogs"], "lens_catalogs")?,
66 kinds: strs("kinds")?,
67 vendor: p["vendor"].as_str().unwrap_or("").to_string(),
68 text: p["text"].as_str().unwrap_or("").to_string(),
69 specs: strs("specs")?,
70 fits: p["fits"].as_f64(),
71 };
72 r.query()?;
73 Ok(r)
74 }
75
76 fn query(&self) -> Result<lensbench_catalog::spec::CatalogQuery, RpcErr> {
78 use lensbench_catalog::spec::{CatalogQuery, ItemKind, SpecFilter};
79 let kinds = self
80 .kinds
81 .iter()
82 .map(|k| {
83 ItemKind::parse(k).ok_or_else(|| RpcErr::params(format!("kinds: unknown kind {k}")))
84 })
85 .collect::<Result<Vec<_>, _>>()?;
86 let specs = self
87 .specs
88 .iter()
89 .map(|s| SpecFilter::parse(s).map_err(RpcErr::params))
90 .collect::<Result<Vec<_>, _>>()?;
91 Ok(CatalogQuery {
92 kinds,
93 vendor: self.vendor.clone(),
94 text: self.text.clone(),
95 specs,
96 fits: self.fits,
97 })
98 }
99}
100
101fn read_all(sess: &Session, v: &[PathBuf]) -> Result<Vec<PathBuf>, RpcErr> {
102 v.iter().map(|x| sess.files.check_path(x, false)).collect()
103}
104
105pub(super) fn glasses(sess: &Session, r: &BrowseReq) -> Result<Value, RpcErr> {
107 Ok(crate::browse::glasses(&read_all(sess, &r.glass_dirs)?))
108}
109
110pub(super) fn lenses(sess: &Session, r: &BrowseReq) -> Result<Value, RpcErr> {
112 let dirs = read_all(sess, &r.glass_dirs)?;
113 let cat = read_all(sess, &r.lens_catalogs)?;
114 Ok(crate::browse::lenses(&cat, &dirs)?)
115}
116
117pub(super) fn catalog_search(sess: &Session, r: &SearchReq) -> Result<Value, RpcErr> {
119 let dirs = read_all(sess, &r.glass_dirs)?;
120 let cat = read_all(sess, &r.lens_catalogs)?;
121 Ok(crate::browse::search(&cat, &dirs, &r.query()?)?)
122}
123
124fn catalog_listing(path: &str, cat: &lensbench_project::UserCatalog) -> Value {
126 let items: Vec<Value> = cat
127 .items
128 .iter()
129 .map(|(k, it)| {
130 json!({ "name": k, "description": it.description, "glass_catalogs": it.glass_catalogs,
131 "blocks": it.blocks().len() })
132 })
133 .collect();
134 json!({ "catalog": path, "vendor": cat.vendor, "items": items })
135}
136
137pub fn range_system(s: &System, from: usize, to: usize) -> lensbench_core::error::Result<System> {
139 let img = s.image();
140 if from == 0 || from > to || to >= img {
141 return Err(lensbench_core::error::Error::Invalid(format!(
142 "surfaces to write {from} to {to} (1 to {})",
143 img - 1
144 )));
145 }
146 let mut s = s.clone();
147 if let Some(stop) = s.surfaces.iter().position(|d| d.stop) {
148 if !(from..=to).contains(&stop) {
149 s.set_stop(from)?;
150 }
151 }
152 for j in (to + 1..img).rev() {
153 s.delete_surface(j)?;
154 }
155 for j in (1..from).rev() {
156 s.delete_surface(j)?;
157 }
158 Ok(s)
159}
160
161#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
164pub struct CatalogAddReq {
165 pub catalog: String,
166 pub name: String,
167 pub blocks: Vec<String>,
168 pub description: String,
169 pub replace: bool,
171 pub vendor: Option<String>,
172}
173
174#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
176pub struct CatalogEditReq {
177 pub catalog: String,
178 pub name: String,
179 pub rename: Option<String>,
180 pub description: Option<String>,
181 pub delete: bool,
182 pub vendor: Option<String>,
183}
184
185pub(super) fn catalog_of(method: &str, p: &Value) -> Result<String, RpcErr> {
187 p["catalog"]
188 .as_str()
189 .filter(|s| !s.trim().is_empty())
190 .map(str::to_string)
191 .ok_or_else(|| RpcErr::params(format!("{method} needs catalog (the user catalog file)")))
192}
193
194fn item_name(method: &str, p: &Value) -> Result<String, RpcErr> {
196 p["name"]
197 .as_str()
198 .map(str::trim)
199 .filter(|s| !s.is_empty())
200 .map(str::to_string)
201 .ok_or_else(|| RpcErr::params(format!("{method} needs name (the item name)")))
202}
203
204impl CatalogAddReq {
205 pub(super) fn parse(p: &Value) -> Result<CatalogAddReq, RpcErr> {
206 let catalog = catalog_of("catalog_add", p)?;
207 let name = item_name("catalog_add", p)?;
208 let blocks: Vec<String> = match (&p["blocks"], &p["block"]) {
209 (Value::Array(a), _) => a
210 .iter()
211 .map(|x| x.as_str().map(str::to_string))
212 .collect::<Option<_>>()
213 .ok_or_else(|| RpcErr::params("blocks must be a list of ids"))?,
214 (_, Value::String(b)) => vec![b.clone()],
215 _ => {
216 return Err(RpcErr::params(
217 "catalog_add needs blocks (a list of block ids)",
218 ))
219 }
220 };
221 Ok(CatalogAddReq {
222 catalog,
223 name,
224 blocks,
225 description: p["description"].as_str().unwrap_or_default().to_string(),
226 replace: p["replace"].as_bool() == Some(true),
227 vendor: p["vendor"].as_str().map(str::to_string),
228 })
229 }
230}
231
232impl CatalogEditReq {
233 pub(super) fn parse(p: &Value) -> Result<CatalogEditReq, RpcErr> {
234 Ok(CatalogEditReq {
235 catalog: catalog_of("catalog_edit", p)?,
236 name: item_name("catalog_edit", p)?,
237 rename: p["rename"].as_str().map(|s| s.trim().to_string()),
238 description: p["description"].as_str().map(str::to_string),
239 delete: p["delete"].as_bool() == Some(true),
240 vendor: p["vendor"].as_str().map(str::to_string),
241 })
242 }
243}
244
245fn set_vendor(cat: &mut lensbench_project::UserCatalog, vendor: &Option<String>) {
246 if let Some(v) = vendor {
247 cat.vendor = v.trim().to_string();
248 }
249}
250
251pub(super) fn catalog_items(sess: &Session, path: &str) -> Result<Value, RpcErr> {
253 let file = sess.files.check_path(Path::new(path), false)?;
254 let cat = lensbench_project::UserCatalog::load(&file)?;
255 Ok(catalog_listing(path, &cat))
256}
257
258pub(super) fn catalog_add(sess: &Session, r: &CatalogAddReq) -> Result<Value, RpcErr> {
260 use lensbench_project::UserCatalog;
261 let (path, name) = (r.catalog.as_str(), r.name.as_str());
262 let file = sess.files.check_path(Path::new(path), true)?;
263 let Current { spec, src, log, .. } = sess.current_full()?;
264 if !is_project(&spec.file) {
265 return Err(RpcErr::app(
266 "catalog_add only works when a project file (combination) is loaded",
267 ));
268 }
269 let cat = UserCatalog::load_or_new(&file)?;
270 if cat.items.contains_key(name) && !r.replace {
271 return Err(RpcErr::app(format!(
272 "item {name} already exists (replace it with replace: true)"
273 )));
274 }
275 let mut pr = src
277 .project()
278 .ok_or_else(|| {
279 RpcErr::app("catalog_add only works when a project file (combination) is loaded")
280 })?
281 .clone();
282 if let Some(st) = &spec.state {
283 pr = pr.with_state(st)?;
284 }
285 let lc = lensbench_core::catalog::LensCatalog::load_registered(&spec.lens_catalog)?;
286 let look = |v: &str, q: &str| lc.zmx(v, q);
287 let env = lensbench_project::Env {
288 step_files: None,
289 base: spec
290 .file
291 .parent()
292 .map(|x| x.to_path_buf())
293 .unwrap_or_default(),
294 glass_dirs: spec.glass_dir.clone(),
295 catalog: Some(&look),
296 };
297 let item = lensbench_project::blocks_item(&pr, &env, &r.blocks, &r.description)?;
298 let cat = UserCatalog::update(&file, |cat| {
299 if cat.items.contains_key(name) && !r.replace {
300 return Err(
301 format!("item {name} already exists (replace it with replace: true)").into(),
302 );
303 }
304 cat.items.insert(name.to_string(), item);
305 set_vendor(cat, &r.vendor);
306 Ok(())
307 })?;
308 let mut out = catalog_listing(path, &cat);
309 out["added"] = json!(name);
310 if !log.is_empty() {
312 out["notes"] = json!([
313 "changes after loading (set, edit) are not in the item (items are made from the project file; save and reload first to include them)"
314 ]);
315 }
316 Ok(out)
317}
318
319pub(super) fn catalog_edit(sess: &Session, r: &CatalogEditReq) -> Result<Value, RpcErr> {
321 let (path, name) = (r.catalog.as_str(), r.name.as_str());
322 let file = sess.files.check_path(Path::new(path), true)?;
323 let mut cat = lensbench_project::UserCatalog::load(&file)?;
324 if !cat.items.contains_key(name) {
325 return Err(RpcErr::app(format!("no item {name}")));
326 }
327 if r.delete {
328 cat.items.remove(name);
329 } else {
330 if let Some(d) = &r.description {
331 cat.items
332 .get_mut(name)
333 .expect("the item exists (looked up above)")
334 .description = d.clone();
335 }
336 if let Some(to) = r.rename.as_deref().map(str::trim) {
337 if to.is_empty() {
338 return Err(RpcErr::params("empty rename name"));
339 }
340 if to != name {
341 if cat.items.contains_key(to) {
342 return Err(RpcErr::app(format!("item {to} already exists")));
343 }
344 let it = cat
345 .items
346 .remove(name)
347 .expect("the item exists (looked up above)");
348 cat.items.insert(to.to_string(), it);
349 }
350 }
351 }
352 set_vendor(&mut cat, &r.vendor);
353 cat.save(&file)?;
354 Ok(catalog_listing(path, &cat))
355}
356
357#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
359pub struct CadStepReq {
360 pub catalog: String,
361 pub item: String,
362 pub cache: Option<String>,
363}
364
365impl CadStepReq {
366 pub(super) fn parse(p: &Value) -> Result<CadStepReq, RpcErr> {
367 Ok(CadStepReq {
368 catalog: need_str("cad_step", p, "catalog")?,
369 item: need_str("cad_step", p, "item")?,
370 cache: p["cache"]
371 .as_str()
372 .map(str::trim)
373 .filter(|x| !x.is_empty())
374 .map(str::to_string),
375 })
376 }
377}
378
379fn need_str(method: &str, p: &Value, k: &str) -> Result<String, RpcErr> {
381 p[k].as_str()
382 .map(str::trim)
383 .filter(|x| !x.is_empty())
384 .map(str::to_string)
385 .ok_or_else(|| {
386 RpcErr::params(match method {
388 "cad_step" => format!("cad_step needs {k}"),
389 _ => format!("catalog_fill needs {k}"),
390 })
391 })
392}
393
394pub(super) fn cad_step(sess: &Session, r: &CadStepReq) -> Result<Value, RpcErr> {
396 #[cfg(target_arch = "wasm32")]
397 {
398 let _ = (sess, r);
399 Err(RpcErr::app(
400 "getting STEP files is not available in the web version",
401 ))
402 }
403 #[cfg(not(target_arch = "wasm32"))]
404 {
405 let src = sess.files.check_path(Path::new(&r.catalog), false)?;
406 let name = r.item.as_str();
407 let cat = lensbench_project::UserCatalog::load(&src)?;
408 let it = cat
409 .items
410 .get(name)
411 .ok_or_else(|| RpcErr::app(format!("no item {name} in {}", src.display())))?;
412 let dir = match &r.cache {
413 Some(d) => sess.files.check_path(Path::new(d), true)?,
414 None => sess
416 .files
417 .check_path(&lensbench_cad::default_cache_dir(), true)?,
418 };
419 lensbench_cad::fetch_item(&dir, name, it)
420 .map(|r| r.to_json())
421 .map_err(|e| {
422 if it.url.is_empty() {
423 RpcErr::app(e)
424 } else {
425 RpcErr::app(format!("{e} (product page: {})", it.url))
426 }
427 })
428 }
429}
430
431#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
438pub struct CatalogFillReq {
439 pub catalog: String,
440 pub out: String,
441 pub item: String,
442 pub thickness: Option<f64>,
443 pub diameter: Option<Value>,
445 pub frame: Option<lensbench_project::MechSpec>,
446 pub from: String,
447 pub frame_reversed: bool,
448 pub spec: Option<Value>,
449 pub glass_visible: bool,
450}
451
452impl CatalogFillReq {
453 pub(super) fn parse(p: &Value) -> Result<CatalogFillReq, RpcErr> {
454 let catalog = need_str("catalog_fill", p, "catalog")?;
455 let out = need_str("catalog_fill", p, "out")?;
456 let item = need_str("catalog_fill", p, "item")?;
457 let frame = match p.get("frame").filter(|v| !v.is_null()) {
458 Some(v) => Some(
459 serde_json::from_value::<lensbench_project::MechSpec>(v.clone())
460 .map_err(|e| RpcErr::params(format!("frame: {e}")))?,
461 ),
462 None => None,
463 };
464 Ok(CatalogFillReq {
465 catalog,
466 out,
467 item,
468 thickness: p["thickness"].as_f64(),
469 diameter: p.get("diameter").filter(|v| !v.is_null()).cloned(),
470 frame,
471 from: p["from"].as_str().unwrap_or("").to_string(),
472 frame_reversed: p["frame_reversed"].as_bool().unwrap_or(false),
473 spec: p.get("spec").filter(|v| v.is_object()).cloned(),
474 glass_visible: p["glass_visible"].as_bool().unwrap_or(false),
475 })
476 }
477}
478
479pub(super) fn catalog_fill(sess: &Session, r: &CatalogFillReq) -> Result<Value, RpcErr> {
481 use lensbench_catalog::fill as cf;
482 use lensbench_project::UserCatalog;
483 let src = sess.files.check_path(Path::new(&r.catalog), false)?;
484 let out = sess.files.check_path(Path::new(&r.out), true)?;
485 let name = r.item.as_str();
486 let cat = UserCatalog::load(&src)?;
487 let it = cat
488 .items
489 .get(name)
490 .ok_or_else(|| RpcErr::app(format!("no item {name} in {}", src.display())))?;
491 if !it.is_incomplete() {
492 return Err(RpcErr::app(format!("{name} is not an incomplete item")));
493 }
494 let vendor = if cat.vendor.trim().is_empty() {
495 src.parent()
496 .and_then(|d| d.file_name())
497 .map(|x| x.to_string_lossy().into_owned())
498 .unwrap_or_default()
499 } else {
500 cat.vendor.clone()
501 };
502 let today = std::time::SystemTime::now()
503 .duration_since(std::time::UNIX_EPOCH)
504 .map(|d| cf::date_of_unix(d.as_secs()))
505 .unwrap_or_default();
506 let mut filled = cf::complete(
507 it,
508 r.thickness,
509 r.diameter.clone(),
510 r.frame.clone(),
511 cf::FillFrom::parse(&r.from),
512 &today,
513 )
514 .map_err(RpcErr::params)?;
515 if let lensbench_project::ItemBody::Optic { frame: Some(f), .. } = &mut filled.body {
516 f.reversed = r.frame_reversed;
517 }
518 if let Some(sv) = &r.spec {
520 let spec = cf::SpecValues::from_value(sv);
521 let num = |k: &str| filled.specs.get(k).and_then(Value::as_f64);
522 let diffs = cf::spec_check(
523 num("thickness"),
524 num("diameter"),
525 filled.frame().map(|f| &f.spec),
526 r.glass_visible,
527 &spec,
528 );
529 for d in diffs.iter().filter(|d| !d.ok()) {
530 filled.notes.push(d.note());
531 }
532 if let (Some(ca), false) = (spec.clear_aperture, it.specs.contains_key("clear_aperture")) {
534 filled
535 .specs
536 .insert("clear_aperture".into(), serde_json::json!(ca));
537 }
538 }
539 let mut fc = UserCatalog::load_or_new(&out)?;
540 if !fc.vendor.is_empty() && fc.vendor != vendor {
541 return Err(RpcErr::app(format!(
542 "{} is a supplementary catalog of maker {} (put {vendor} items in another file)",
543 out.display(),
544 fc.vendor
545 )));
546 }
547 fc.vendor = vendor.clone();
548 for (k, v) in &cat.coatings {
550 fc.coatings.entry(k.clone()).or_insert_with(|| v.clone());
551 }
552 fc.items.insert(name.to_string(), filled.clone());
553 if let Some(d) = out.parent().filter(|d| !d.as_os_str().is_empty()) {
554 lensbench_core::vfs::create_dir_all(d)
555 .map_err(|e| RpcErr::app(format!("{}: {e}", d.display())))?;
556 }
557 fc.save(&out)?;
558 Ok(json!({
559 "catalog": out.display().to_string(),
560 "item": name,
561 "vendor": vendor,
562 "specs": filled.specs,
563 "notes": filled.notes,
564 "frame": filled.frame().map(|f| &f.spec),
565 "frame_reversed": filled.frame().is_some_and(|f| f.reversed),
566 }))
567}