1use lensbench_core::{LockExt, RwLockExt};
10use std::collections::HashMap;
11use std::path::{Path, PathBuf};
12use std::sync::{Arc, Mutex};
13use web_time::Instant;
14
15use lensbench_core::coating::C64;
16use lensbench_core::history::History;
17use lensbench_core::system::Launch;
18use lensbench_core::System;
19use lensbench_export::d2::Plane;
20use lensbench_formats::zmx_write;
21use serde_json::{json, Map, Value};
22
23use crate::load::{read_file_notes, Faces, ReadFile, SysSpec as LoadSpec};
24use lensbench_project::open::Source;
25use lensbench_project::retarget::Retarget;
26use lensbench_project::{BlockSpans, FaceId};
27
28pub enum Files {
30 Any,
32 Root(PathBuf),
34 Deny,
36}
37
38impl Files {
41 pub fn check_terms(&self, t: &mut Value) -> lensbench_core::Result<()> {
43 Ok(self.check_term_paths(t).map_err(|e| e.msg)?)
44 }
45
46 pub(crate) fn check_term_paths(&self, t: &mut Value) -> Result<(), RpcErr> {
47 let limited = !matches!(self, Files::Any);
48 let items: Vec<&mut Value> = match t {
49 Value::Array(a) => a.iter_mut().collect(),
50 x => vec![x],
51 };
52 for x in items {
53 let Some(o) = x.as_object_mut() else { continue };
54 let ty = o.get("type").and_then(Value::as_str).unwrap_or_default();
55 if !ty.eq_ignore_ascii_case("zplm") {
56 continue;
57 }
58 if let Some(f) = o.get_mut("file") {
59 if let Some(p) = f.as_str() {
60 *f = json!(self.check_path(Path::new(p), false)?.to_string_lossy());
61 }
62 }
63 if let Some(Value::Array(ds)) = o.get_mut("macro_dirs") {
64 for d in ds.iter_mut() {
65 if let Some(p) = d.as_str() {
66 *d = json!(self.check_path(Path::new(p), false)?.to_string_lossy());
67 }
68 }
69 }
70 if limited {
71 o.insert("default_dirs".into(), json!(false));
72 }
73 }
74 Ok(())
75 }
76
77 pub(crate) fn check_path(&self, p: &Path, write: bool) -> Result<PathBuf, RpcErr> {
79 match self {
80 Files::Any => Ok(p.to_path_buf()),
81 Files::Deny => Err(RpcErr::app(format!(
82 "{}: with --allow-remote, requests don't read or write files (limit the place with --root to allow it)",
83 p.display()
84 ))),
85 Files::Root(root) => {
86 let q = if p.is_absolute() {
87 p.to_path_buf()
88 } else {
89 root.join(p)
90 };
91 let bad = || RpcErr::app(format!("{} is outside --root", p.display()));
92 let real = match q.canonicalize() {
94 Ok(r) => r,
95 Err(_) if write => {
96 let name = q.file_name().filter(|n| *n != "..").ok_or_else(bad)?;
97 let dir = q.parent().ok_or_else(bad)?;
98 let dir = dir.canonicalize().map_err(|e| {
99 RpcErr::app(format!("{}: {e}", dir.display()))
100 })?;
101 dir.join(name)
102 }
103 Err(e) => return Err(RpcErr::app(format!("{}: {e}", p.display()))),
104 };
105 if real.starts_with(root) {
106 Ok(real)
107 } else {
108 Err(bad())
109 }
110 }
111 }
112 }
113}
114
115#[derive(Clone)]
117enum Change {
118 Set(Vec<(String, f64, f64)>),
120 Edit(Vec<lensbench_project::edit_ops::EditOp>),
122}
123
124struct Served {
125 sys: Arc<System>,
126 spec: LoadSpec,
127 src: Arc<Source>,
129 blocks: Arc<Vec<BlockSpans>>,
131 faces: Arc<Faces>,
133 notes: Vec<String>,
135 log: Vec<Change>,
136 hist: History<Snap, Value>,
138 last_set: Option<(Vec<String>, Instant)>,
140}
141
142pub(crate) struct Current {
144 sys: Arc<System>,
146 spec: LoadSpec,
147 src: Arc<Source>,
149 faces: Arc<Faces>,
151 log: Vec<Change>,
153}
154
155fn active_cfg(cur: &System, spec: &LoadSpec) -> usize {
157 cur.configs.as_ref().map_or(spec.cfg, |t| t.active)
158}
159
160#[derive(Clone)]
162struct Snap {
163 sys: Arc<System>,
164 spec: LoadSpec,
165 src: Arc<Source>,
166 blocks: Arc<Vec<BlockSpans>>,
167 faces: Arc<Faces>,
168 notes: Vec<String>,
169 log: Vec<Change>,
170}
171const SET_MERGE_S: f64 = 1.0;
173
174pub struct Session {
179 pub(crate) files: Files,
180 served: Mutex<Option<Served>>,
181 request: std::sync::RwLock<()>,
183 long: Mutex<()>,
185 pending_apply: Mutex<Option<PendingApply>>,
187 running: Mutex<Vec<lensbench_core::par::CancelToken>>,
189 opt_run: optim::JobSlot,
191 tol_run: optim::JobSlot,
192 swap_run: optim::JobSlot,
193}
194
195impl Default for Session {
196 fn default() -> Self {
197 Self::with_files(Files::Any)
198 }
199}
200
201pub fn global() -> &'static Session {
203 static G: std::sync::OnceLock<Session> = std::sync::OnceLock::new();
204 G.get_or_init(Session::default)
205}
206
207impl Session {
208 pub fn new() -> Self {
210 Self::default()
211 }
212
213 pub fn with_files(files: Files) -> Self {
215 Session {
216 files,
217 served: Mutex::new(None),
218 request: std::sync::RwLock::new(()),
219 long: Mutex::new(()),
220 pending_apply: Mutex::new(None),
221 running: Mutex::new(Vec::new()),
222 opt_run: Default::default(),
223 tol_run: Default::default(),
224 swap_run: Default::default(),
225 }
226 }
227
228 pub fn open(&self, spec: LoadSpec, threads: Option<usize>) -> lensbench_core::Result<()> {
230 let r = lensbench_core::with_threads(threads, || read_file_notes(&spec))?;
231 store(self, r, spec);
232 Ok(())
233 }
234
235 pub fn files(&self) -> &Files {
237 &self.files
238 }
239
240 pub fn handle(
242 &self,
243 method: &str,
244 params: &Value,
245 bins: Vec<Bin>,
246 threads: Option<usize>,
247 ) -> Result<(Value, Vec<Bin>), CallError> {
248 dispatch(self, method, params, bins, threads)
249 .and_then(|(a, b)| Ok((a.into_json()?, b)))
250 .map_err(CallError::from)
251 }
252
253 fn served(&self) -> std::sync::MutexGuard<'_, Option<Served>> {
254 self.served.lock_ok()
255 }
256
257 pub(crate) fn current_system(&self) -> Result<Arc<System>, RpcErr> {
259 Ok(self.current()?.0)
260 }
261
262 fn current_full(&self) -> Result<Current, RpcErr> {
264 self.served()
265 .as_ref()
266 .map(|x| Current {
267 sys: x.sys.clone(),
268 spec: x.spec.clone(),
269 src: x.src.clone(),
270 faces: x.faces.clone(),
271 log: x.log.clone(),
272 })
273 .ok_or_else(|| RpcErr::app("no system (load first)"))
274 }
275
276 fn current(&self) -> Result<(Arc<System>, LoadSpec), RpcErr> {
277 self.served()
278 .as_ref()
279 .map(|x| (x.sys.clone(), x.spec.clone()))
280 .ok_or_else(|| RpcErr::app("no system (load first)"))
281 }
282}
283
284fn store(sess: &Session, r: ReadFile, spec: LoadSpec) {
286 *sess.served() = Some(Served {
287 sys: Arc::new(r.sys),
288 spec,
289 src: Arc::new(r.src),
290 blocks: Arc::new(r.blocks),
291 faces: Arc::new(r.faces),
292 notes: r.notes,
293 log: Vec::new(),
294 hist: History::default(),
295 last_set: None,
296 });
297}
298
299fn store_loaded(sess: &Session, r: ReadFile, spec: LoadSpec, h: LoadHistory, reload: bool) {
301 let mut g = sess.served();
302 let Some(mut x) = g.take().filter(|_| h != LoadHistory::Clear) else {
303 drop(g);
304 store(sess, r, spec);
305 return;
306 };
307 if h == LoadHistory::Push {
308 let name = spec
309 .file
310 .file_name()
311 .map(|f| f.to_string_lossy().into_owned())
312 .unwrap_or_default();
313 let what = if reload {
314 json!({ "reload": name })
315 } else {
316 json!({ "open": name })
317 };
318 push_undo(&mut x, what);
319 }
320 x.sys = Arc::new(r.sys);
321 x.spec = spec;
322 x.src = Arc::new(r.src);
323 x.blocks = Arc::new(r.blocks);
324 x.faces = Arc::new(r.faces);
325 x.notes = r.notes;
326 x.log = Vec::new();
327 x.last_set = None;
328 *g = Some(x);
329}
330
331mod answer;
332use answer::surfaces_view;
333pub use answer::Answer;
334mod request;
335mod run;
336pub use request::{AnalyzeReq, GetReq, LoadHistory, LoadReq, Request, ThermalReq};
337#[path = "session_hist.rs"]
338mod hist;
339
340mod args;
341mod catalog;
342mod layout;
343mod optim;
344mod proto;
345mod replay;
346mod save_project;
347mod trace;
348pub mod views;
349use args::{known_keys, opt_f64, opt_usize, str_list};
350pub use catalog::range_system;
351pub use catalog::{
352 BrowseReq, CadStepReq, CatalogAddReq, CatalogEditReq, CatalogFillReq, SearchReq,
353};
354use hist::{change_label, config_only, history_json, snap_was_load, summary, CONFIG_KEY};
355use layout::{configs, layout, layout_export, layout_with};
356pub use layout::{LayoutExportReq, LayoutReq};
357use optim::{apply_pending, optimize, swap, tolerance, zoom, PendingApply};
358pub use optim::{
359 optimize_cancel, optimize_progress, swap_cancel, swap_progress, tolerance_cancel,
360 tolerance_progress,
361};
362pub use optim::{SwapReq, TolReq};
363pub use proto::{Access, METHODS, PROTOCOL};
364use replay::replay;
365use trace::{plugin, trace};
366pub use trace::{PluginInput, PluginReq, PluginValue, TraceReq};
367
368fn snap(x: &Served) -> Snap {
370 Snap {
371 sys: x.sys.clone(),
372 spec: x.spec.clone(),
373 src: x.src.clone(),
374 blocks: x.blocks.clone(),
375 faces: x.faces.clone(),
376 notes: x.notes.clone(),
377 log: x.log.clone(),
378 }
379}
380
381fn push_undo(x: &mut Served, what: Value) {
383 let s = snap(x);
384 x.hist.record(s, what);
385}
386
387fn store_changed(sess: &Session, sys: System, spec: LoadSpec, c: Change) {
389 let mut g = sess.served();
390 let Some(mut x) = g.take() else {
392 return;
393 };
394 let now = Instant::now();
395 let names = match &c {
397 Change::Set(v) => Some(v.iter().map(|r| r.0.clone()).collect::<Vec<_>>()),
398 Change::Edit(o) => config_only(o).then(|| vec![CONFIG_KEY.to_string()]),
399 };
400 let merge = matches!((&names, &x.last_set), (Some(n), Some((m, t))) if n == m
401 && (n[..] == [CONFIG_KEY] || now.duration_since(*t).as_secs_f64() < SET_MERGE_S));
402 let s = snap(&x);
403 x.hist.record_or_merge(s, change_label(Some(&c)), merge);
404 if sys.surfaces.len() != x.sys.surfaces.len() || moves_surfaces(&c) {
406 x.blocks = Arc::default();
407 }
408 x.last_set = names.map(|n| (n, now));
409 x.log.push(c);
410 x.sys = Arc::new(sys);
411 x.spec = spec;
412 *g = Some(x);
413}
414
415fn moves_surfaces(c: &Change) -> bool {
417 use lensbench_project::edit_ops::EditOp as O;
418 matches!(c, Change::Edit(ops) if ops.iter().any(|o| matches!(o, O::InsertSurface { .. } | O::DeleteSurface { .. })))
419}
420
421fn step_history(sess: &Session, back: bool) -> Result<Value, RpcErr> {
423 let mut g = sess.served();
424 let x = g
425 .as_mut()
426 .ok_or_else(|| RpcErr::app("no system (load first)"))?;
427 let cur = snap(x);
428 let Some(snap) = x.hist.step(cur, back) else {
429 return Err(RpcErr::app(if back {
430 "no change to undo"
431 } else {
432 "no change to redo"
433 }));
434 };
435 let file0 = std::mem::replace(&mut x.spec, snap.spec).file;
436 x.sys = snap.sys;
437 x.src = snap.src;
438 x.blocks = snap.blocks;
439 x.faces = snap.faces;
440 x.notes = snap.notes;
441 x.log = snap.log;
442 x.last_set = None;
443 let hash = lensbench_project::sysfile::system_hash(&x.sys).map_err(RpcErr::app)?;
444 let mut v = history_json(x);
445 v["surfaces"] = json!(x.sys.surfaces.len());
446 v["system_hash"] = json!(hash);
447 if x.spec.file != file0 || snap_was_load(&v, back) {
449 v["loaded"] = summary(&x.sys, &x.spec, &x.notes, &x.blocks);
450 }
451 Ok(v)
452}
453
454fn history(sess: &Session) -> Value {
456 sess.served()
457 .as_ref()
458 .map_or_else(|| json!(views::HistoryView::default()), history_json)
459}
460
461fn add_history(sess: &Session, v: &mut Value) {
463 if let (Some(o), Value::Object(h)) = (v.as_object_mut(), history(sess)) {
464 o.extend(h);
465 }
466}
467
468fn step_history_n(sess: &Session, back: bool, n: usize) -> Result<Value, RpcErr> {
470 let mut v = step_history(sess, back)?;
471 let mut loaded = v.get("loaded").is_some();
472 for _ in 1..n {
473 match step_history(sess, back) {
474 Ok(w) => {
475 loaded |= w.get("loaded").is_some();
476 v = w;
477 }
478 Err(_) => break,
479 }
480 }
481 if loaded && v.get("loaded").is_none() {
483 if let Some(x) = sess.served().as_ref() {
484 v["loaded"] = summary(&x.sys, &x.spec, &x.notes, &x.blocks);
485 }
486 }
487 Ok(v)
488}
489
490pub(crate) struct RpcErr {
492 code: i64,
493 pub(crate) msg: String,
494 kind: Option<&'static str>,
496 ecode: Option<&'static str>,
498}
499
500impl RpcErr {
501 fn app(m: impl Into<String>) -> Self {
502 RpcErr {
503 code: -32000,
504 msg: m.into(),
505 kind: None,
506 ecode: None,
507 }
508 }
509 pub(crate) fn with_core(self, e: &lensbench_core::Error) -> Self {
511 RpcErr {
512 kind: Some(e.kind()),
513 ecode: Some(e.code()),
514 ..self
515 }
516 }
517 pub(crate) fn params(m: impl Into<String>) -> Self {
518 RpcErr {
519 code: -32602,
520 msg: m.into(),
521 kind: None,
522 ecode: None,
523 }
524 }
525}
526
527impl From<String> for RpcErr {
529 fn from(m: String) -> Self {
530 RpcErr::app(lensbench_core::i18n::tr(&m))
531 }
532}
533
534impl From<lensbench_core::Error> for RpcErr {
535 fn from(e: lensbench_core::Error) -> Self {
536 RpcErr::app(e.to_string()).with_core(&e)
537 }
538}
539
540impl From<lensbench_project::ExpandError> for RpcErr {
542 fn from(e: lensbench_project::ExpandError) -> Self {
543 lensbench_core::Error::from(e).into()
544 }
545}
546
547impl From<RpcErr> for CallError {
548 fn from(e: RpcErr) -> Self {
549 CallError {
550 code: e.code,
551 message: e.msg,
552 kind: e.kind.map(str::to_string),
553 data_code: e.ecode.map(str::to_string),
554 }
555 }
556}
557
558#[derive(Debug, Clone, PartialEq)]
560pub enum Data {
561 F64(Vec<f64>),
562 I32(Vec<i32>),
563 U8(Vec<u8>),
564 C64(Vec<C64>),
565 Bool(Vec<bool>),
566}
567
568#[derive(Debug, Clone, PartialEq)]
570pub struct Bin {
571 pub name: String,
572 pub shape: Vec<usize>,
573 pub data: Data,
574}
575
576impl Bin {
577 pub fn f64(name: &str, v: Vec<f64>) -> Bin {
578 Bin {
579 name: name.into(),
580 shape: vec![v.len()],
581 data: Data::F64(v),
582 }
583 }
584 pub fn i32(name: &str, v: Vec<i32>) -> Bin {
585 Bin {
586 name: name.into(),
587 shape: vec![v.len()],
588 data: Data::I32(v),
589 }
590 }
591 pub fn dtype(&self) -> &'static str {
593 match self.data {
594 Data::F64(_) => "<f8",
595 Data::I32(_) => "<i4",
596 Data::U8(_) => "|u1",
597 Data::C64(_) => "<c16",
598 Data::Bool(_) => "|b1",
599 }
600 }
601 pub fn header(&self) -> Value {
603 json!({ "name": self.name, "dtype": self.dtype(), "shape": self.shape })
604 }
605 pub fn write_to(&self, out: &mut Vec<u8>) {
607 match &self.data {
608 Data::F64(v) => {
609 out.reserve(v.len() * 8);
610 for x in v {
611 out.extend_from_slice(&x.to_le_bytes());
612 }
613 }
614 Data::I32(v) => {
615 out.reserve(v.len() * 4);
616 for x in v {
617 out.extend_from_slice(&x.to_le_bytes());
618 }
619 }
620 Data::U8(v) => out.extend_from_slice(v),
621 Data::C64(v) => {
622 out.reserve(v.len() * 16);
623 for x in v {
624 out.extend_from_slice(&x.re.to_le_bytes());
625 out.extend_from_slice(&x.im.to_le_bytes());
626 }
627 }
628 Data::Bool(v) => out.extend(v.iter().map(|&b| b as u8)),
629 }
630 }
631}
632
633thread_local! {
634 static LAST_PANIC: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
636}
637
638pub fn note_panic(text: &str) {
640 LAST_PANIC.with(|l| *l.borrow_mut() = Some(text.to_string()));
641}
642
643fn dispatch(
645 sess: &Session,
646 method: &str,
647 params: &Value,
648 bins: Vec<Bin>,
649 threads: Option<usize>,
650) -> Result<(Answer, Vec<Bin>), RpcErr> {
651 if let Some(r) = status(sess, method, params) {
653 return r.map(|(v, b)| (Answer::Json(v), b));
654 }
655 let req = catch_panic(|| Request::parse(method, params))?;
657 dispatch_req(sess, req, bins, threads)
658}
659
660pub(crate) fn catch_panic<T>(f: impl FnOnce() -> Result<T, RpcErr>) -> Result<T, RpcErr> {
662 LAST_PANIC.with(|l| l.borrow_mut().take());
663 std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|e| {
664 let t = LAST_PANIC
666 .with(|l| l.borrow_mut().take())
667 .or_else(|| e.downcast_ref::<&str>().map(|s| s.to_string()))
668 .or_else(|| e.downcast_ref::<String>().cloned());
669 Err(RpcErr::app(match t {
670 Some(t) => format!("internal error (panic): {t}"),
671 None => "internal error (panic)".into(),
672 }))
673 })
674}
675
676fn dispatch_req(
678 sess: &Session,
679 req: Request,
680 bins: Vec<Bin>,
681 threads: Option<usize>,
682) -> Result<(Answer, Vec<Bin>), RpcErr> {
683 let (_r, _w, _l);
684 let access = Access::of(req.method());
685 match access {
686 Access::Read => _r = sess.request.read_ok(),
687 Access::Write => _w = sess.request.write_ok(),
688 Access::Long => _l = sess.long.lock_ok(),
690 }
691 let tok = lensbench_core::par::current().cancel.unwrap_or_default();
693 sess.running.lock_ok().push(tok.clone());
694 struct Done<'a>(&'a Session, lensbench_core::par::CancelToken);
695 impl Drop for Done<'_> {
696 fn drop(&mut self) {
697 let mut r = self.0.running.lock_ok();
698 if let Some(i) = r.iter().position(|t| t.same(&self.1)) {
699 r.swap_remove(i);
700 }
701 }
702 }
703 let _d = Done(sess, tok.clone());
704 let run = || {
705 catch_panic(|| lensbench_core::par::with_cancel(Some(&tok), || run::run(sess, req, bins)))
706 };
707 if access != Access::Long {
708 return lensbench_core::with_threads(threads, run);
709 }
710 let r = lensbench_core::par::with_threads_apart(threads, run);
712 let p = sess.pending_apply.lock_ok().take();
713 match (r, p) {
714 (Ok((mut v, b)), Some(p)) => {
715 apply_pending(sess, p, &mut v);
716 Ok((v, b))
717 }
718 (r, _) => r,
719 }
720}
721
722fn status(sess: &Session, method: &str, p: &Value) -> Option<Result<Reply, RpcErr>> {
726 let r = match method {
727 "progress" => json!({
728 "running": !sess.running.lock_ok().is_empty(),
729 "optimize": sess.optimize_progress(),
730 "tolerance": sess.tolerance_progress(),
731 "swap": sess.swap_progress(),
732 }),
733 "cancel" => {
734 let r = sess.running.lock_ok();
735 r.iter().for_each(|t| t.cancel());
736 json!(!r.is_empty())
737 }
738 "stop" => match p["what"].as_str() {
739 Some("optimize") => {
740 sess.optimize_cancel();
741 json!(true)
742 }
743 Some("tolerance") => {
744 sess.tolerance_cancel();
745 json!(true)
746 }
747 Some("swap") => {
748 sess.swap_cancel();
749 json!(true)
750 }
751 _ => {
752 return Some(Err(RpcErr::params(
753 "stop what must be optimize, tolerance or swap",
754 )))
755 }
756 },
757 _ => return None,
758 };
759 Some(Ok((r, Vec::new())))
760}
761
762#[derive(Debug, Clone, PartialEq)]
764pub struct CallError {
765 pub code: i64,
766 pub message: String,
767 pub kind: Option<String>,
769 pub data_code: Option<String>,
771}
772
773impl std::fmt::Display for CallError {
774 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
775 f.write_str(&self.message)
776 }
777}
778
779pub type Arrays = Vec<(String, Vec<f64>)>;
781
782impl Session {
783 pub fn call(
787 &self,
788 method: &str,
789 params: &Value,
790 threads: Option<usize>,
791 ) -> Result<Value, CallError> {
792 self.call_arrays(method, params, threads).map(|(v, _)| v)
793 }
794
795 pub fn call_arrays(
797 &self,
798 method: &str,
799 params: &Value,
800 threads: Option<usize>,
801 ) -> Result<(Value, Arrays), CallError> {
802 let (a, arrays) = self.call_answer(method, params, threads)?;
803 Ok((
804 a.into_json()
805 .map_err(|e| CallError::from(RpcErr::from(e)))?,
806 arrays,
807 ))
808 }
809
810 pub fn call_answer(
813 &self,
814 method: &str,
815 params: &Value,
816 threads: Option<usize>,
817 ) -> Result<(Answer, Arrays), CallError> {
818 dispatch(self, method, params, Vec::new(), threads)
819 .map(arrays_of)
820 .map_err(CallError::from)
821 }
822
823 pub fn request(
825 &self,
826 req: Request,
827 threads: Option<usize>,
828 ) -> Result<(Answer, Arrays), CallError> {
829 let r = match req {
830 Request::Json { method, params } => {
832 dispatch(self, &method, ¶ms, Vec::new(), threads)
833 }
834 req => dispatch_req(self, req, Vec::new(), threads),
835 };
836 r.map(arrays_of).map_err(CallError::from)
837 }
838
839 pub fn preview_layout(&self, load: &Value, opts: &Value) -> Result<Value, CallError> {
842 let f = || -> Result<(LoadReq, LayoutReq), RpcErr> {
843 Ok((LoadReq::parse(load)?, LayoutReq::parse(opts)?))
844 };
845 let (l, o) = f().map_err(CallError::from)?;
846 self.preview(&l, &o)
847 }
848
849 pub fn preview(&self, load: &LoadReq, opts: &LayoutReq) -> Result<Value, CallError> {
851 let f = || preview_of(self, load, opts);
852 std::panic::catch_unwind(std::panic::AssertUnwindSafe(f))
853 .unwrap_or_else(|_| Err(RpcErr::app("internal error (panic)")))
854 .map_err(CallError::from)
855 }
856
857 pub fn catalog(&self, req: &Request) -> Result<Value, CallError> {
861 let sess = self;
862 let f = || match req {
863 Request::Glasses(r) => catalog::glasses(sess, r),
864 Request::Lenses(r) => catalog::lenses(sess, r),
865 Request::CatalogSearch(r) => catalog::catalog_search(sess, r),
866 Request::CatalogItems { catalog } => catalog::catalog_items(sess, catalog),
867 Request::CatalogEdit(r) => catalog::catalog_edit(sess, r),
868 Request::CatalogFill(r) => catalog::catalog_fill(sess, r),
869 r => {
870 let m = r.method();
871 Err(RpcErr::params(format!(
872 "{m} must be glasses, lenses, catalog_search, catalog_items, catalog_edit or catalog_fill"
873 )))
874 }
875 };
876 std::panic::catch_unwind(std::panic::AssertUnwindSafe(f))
877 .unwrap_or_else(|_| Err(RpcErr::app("internal error (panic)")))
878 .map_err(CallError::from)
879 }
880
881 pub fn browse(&self, method: &str, params: &Value) -> Result<Value, CallError> {
883 self.catalog(&Request::from_json(method, params)?)
884 }
885}
886
887fn preview_of(sess: &Session, load: &LoadReq, opts: &LayoutReq) -> Result<Value, RpcErr> {
889 let spec = load.spec(sess)?;
890 let r = read_file_notes(&spec)?;
891 let mut v = layout_with(&r.sys, &spec, opts, None)?;
892 v["blocks"] = json!(r.blocks);
894 Ok(v)
895}
896
897fn arrays_of((v, bins): (Answer, Vec<Bin>)) -> (Answer, Arrays) {
899 let a = bins
900 .into_iter()
901 .flat_map(|b| {
902 let d = match b.data {
903 Data::F64(x) => x,
904 Data::I32(x) => x.into_iter().map(f64::from).collect(),
905 Data::U8(x) => x.into_iter().map(f64::from).collect(),
906 Data::Bool(x) => x.into_iter().map(|b| b as u8 as f64).collect(),
907 Data::C64(x) => {
909 let im = x.iter().map(|z| z.im).collect();
910 return vec![
911 (format!("{}.re", b.name), x.iter().map(|z| z.re).collect()),
912 (format!("{}.im", b.name), im),
913 ];
914 }
915 };
916 vec![(b.name, d)]
917 })
918 .collect();
919 (v, a)
920}
921
922pub fn call(method: &str, params: &Value, threads: Option<usize>) -> Result<Value, CallError> {
924 global().call(method, params, threads)
925}
926
927pub fn call_arrays(
929 method: &str,
930 params: &Value,
931 threads: Option<usize>,
932) -> Result<(Value, Arrays), CallError> {
933 global().call_arrays(method, params, threads)
934}
935
936pub fn request(req: Request, threads: Option<usize>) -> Result<(Answer, Arrays), CallError> {
938 global().request(req, threads)
939}
940
941pub fn call_answer(
943 method: &str,
944 params: &Value,
945 threads: Option<usize>,
946) -> Result<(Answer, Arrays), CallError> {
947 global().call_answer(method, params, threads)
948}
949
950pub fn preview_layout(load: &Value, opts: &Value) -> Result<Value, CallError> {
952 global().preview_layout(load, opts)
953}
954
955pub fn preview(load: &LoadReq, opts: &LayoutReq) -> Result<Value, CallError> {
957 global().preview(load, opts)
958}
959
960pub fn catalog(req: &Request) -> Result<Value, CallError> {
962 global().catalog(req)
963}
964
965pub fn browse(method: &str, params: &Value) -> Result<Value, CallError> {
967 global().browse(method, params)
968}
969
970type Reply = (Value, Vec<Bin>);
971
972fn answer(method: &str, p: &Value, bins: Vec<Bin>) -> Result<(Answer, Vec<Bin>), RpcErr> {
974 handle(method, p, bins).map(|(v, b)| (Answer::Json(v), b))
975}
976
977fn handle(method: &str, p: &Value, bins: Vec<Bin>) -> Result<Reply, RpcErr> {
978 match method {
979 "echo" => Ok((json!({ "params": p }), bins)),
981 "" => Err(RpcErr {
982 code: -32600,
983 msg: "no method".into(),
984 kind: None,
985 ecode: None,
986 }),
987 m => Err(RpcErr {
988 code: -32601,
989 msg: format!("no method {m}"),
990 kind: None,
991 ecode: None,
992 }),
993 }
994}
995
996fn parse_changes(
998 s: &System,
999 values: &[(String, f64)],
1000) -> Result<Vec<(lensbench_core::param::Param, f64)>, RpcErr> {
1001 values.iter().map(|(k, v)| Ok((s.param(k)?, *v))).collect()
1002}
1003
1004fn analyze(sess: &Session, r: &AnalyzeReq) -> Result<Answer, RpcErr> {
1006 sess.current()?;
1007 let (cmd, m) = (r.cmd.as_str(), &r.args);
1008 if cmd == "coatings" {
1009 return crate::analyze::coatings_loaded(sess, m).map(Answer::Json);
1010 }
1011 match crate::analyses().get(cmd).cloned() {
1012 Some(def) => crate::analyze::run(sess, def.as_ref(), m),
1013 None => Err(RpcErr::params(match cmd {
1014 "optimize" | "tolerance" | "swap" | "zoom" | "layout" => format!(
1015 "{cmd} is not an analyze analysis (use method {})",
1016 if cmd == "layout" {
1017 "layout_export"
1018 } else {
1019 cmd
1020 }
1021 ),
1022 _ => format!(
1023 "{cmd} is not an analyze analysis (list them with analysis_args or plugins)"
1024 ),
1025 })),
1026 }
1027}
1028
1029pub(crate) fn with_source<R>(
1031 sess: &Session,
1032 f: impl FnOnce(&dyn lensbench_analysis::Source) -> R,
1033) -> Result<R, RpcErr> {
1034 let Current {
1035 sys,
1036 spec,
1037 src,
1038 faces,
1039 log,
1040 } = sess.current_full()?;
1041 let r = |s: System, to: &[Option<FaceId>], l: &str, n: &mut Vec<String>| {
1042 replay(s, &log, (&faces, to), l, n)
1043 };
1044 Ok(f(&crate::source::FileSource::loaded(&spec, src, &sys, &r)))
1045}
1046
1047fn is_zmx(f: &Path) -> bool {
1048 f.extension().is_some_and(|x| x.eq_ignore_ascii_case("zmx"))
1049}
1050
1051fn config_diff(spec: &LoadSpec, src: &Source) -> Result<Value, RpcErr> {
1053 use lensbench_core::param::{Kind, Param};
1054 if !is_zmx(&spec.file) {
1055 return Err(RpcErr::params("config_diff is only for .zmx systems"));
1056 }
1057 let n = src.configurations()?;
1059 if n < 2 {
1060 return Err(RpcErr::app("this .zmx has no multiple configurations"));
1061 }
1062 let mut systems = Vec::with_capacity(n);
1063 for k in 1..=n {
1064 let mut c = spec.clone();
1065 c.cfg = k;
1066 systems.push(
1067 crate::load::load_source(src, &c).map_err(|e| e.at(format!("configuration {k}")))?,
1068 );
1069 }
1070 let m = systems[0].surfaces.len();
1071 if systems.iter().any(|s| s.surfaces.len() != m) {
1072 return Err(RpcErr::app(
1073 "the configurations have different numbers of surfaces (no table)",
1074 ));
1075 }
1076 let mut kinds = vec![Kind::Curv, Kind::Conic, Kind::Thick];
1077 kinds.extend((0..8).map(Kind::Asph));
1078 kinds.extend([
1079 Kind::Dx,
1080 Kind::Dy,
1081 Kind::Tx,
1082 Kind::Ty,
1083 Kind::Tz,
1084 Kind::Dn,
1085 Kind::Disp,
1086 ]);
1087 let mut ops = vec![json!({ "op": "set_config_count", "n": n })];
1088 let mut notes = Vec::new();
1089 for j in 0..m {
1090 for &kind in &kinds {
1091 let p = Param::new(j, kind);
1092 let vals: Option<Vec<f64>> = systems.iter().map(|s| s.get_param(p).ok()).collect();
1093 let Some(vals) = vals else { continue };
1094 if vals.iter().any(|v| v.to_bits() != vals[0].to_bits()) {
1095 ops.push(json!({
1096 "op": "set_config_row", "param": systems[0].param_name(p), "values": vals,
1097 }));
1098 }
1099 }
1100 let differs = |f: &dyn Fn(&System) -> String| {
1101 let a = f(&systems[0]);
1102 systems.iter().any(|s| f(s) != a)
1103 };
1104 type Get = fn(&lensbench_core::surface::Surface) -> String;
1105 if differs(&|s| s.surfaces[j].mat.name()) {
1106 let names: Vec<String> = systems.iter().map(|s| s.surfaces[j].mat.name()).collect();
1107 ops.push(json!({
1108 "op": "set_config_materials",
1109 "param": systems[0].param_name(Param::new(j, Kind::Material)),
1110 "names": names,
1111 }));
1112 }
1113 if differs(&|s| s.surfaces[j].coat.clone()) {
1114 let names: Vec<String> = systems.iter().map(|s| s.surfaces[j].coat.clone()).collect();
1115 ops.push(json!({
1116 "op": "set_config_coatings",
1117 "param": systems[0].param_name(Param::new(j, Kind::Coating)),
1118 "names": names,
1119 }));
1120 }
1121 let checks: [(&str, Get); 3] = [
1122 ("ignore", |d| d.ignore.to_string()),
1123 ("semi-diameter", |d| format!("{:?}", d.semi)),
1124 ("stop", |d| d.stop.to_string()),
1125 ];
1126 for (what, f) in checks {
1127 if differs(&|s| f(&s.surfaces[j])) {
1128 notes.push(format!(
1129 "surface {j}: {what} differs by configuration (can't tabulate)"
1130 ));
1131 }
1132 }
1133 }
1134 let differs_sys = |f: &dyn Fn(&System) -> String| {
1135 let a = f(&systems[0]);
1136 systems.iter().any(|s| f(s) != a)
1137 };
1138 if differs_sys(&|s| format!("{:?}", s.wavelengths)) {
1139 notes.push("wavelengths differ by configuration (can't tabulate)".into());
1140 }
1141 if differs_sys(&|s| format!("{:?}", s.fields)) {
1142 notes.push("fields differ by configuration (can't tabulate)".into());
1143 }
1144 ops.push(json!({ "op": "set_config", "k": spec.cfg.clamp(1, n) }));
1145 Ok(json!({ "ops": ops, "notes": notes, "rows": ops.len() - 2 }))
1146}
1147
1148fn is_project(f: &Path) -> bool {
1150 lensbench_project::open::FileKind::of(f) == lensbench_project::open::FileKind::Project
1151}