1use serde::{Deserialize, Serialize};
12
13#[cfg(feature = "codegen")]
14use schemars::JsonSchema;
15#[cfg(feature = "codegen")]
16use ts_rs::TS;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
20#[serde(rename_all = "lowercase")]
21#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
22#[cfg_attr(feature = "codegen", ts(export))]
23pub enum TextAnchor {
24 Start,
25 Middle,
26 End,
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
33#[serde(rename_all = "lowercase")]
34#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
35#[cfg_attr(feature = "codegen", ts(export))]
36pub enum LayerName {
37 Shading,
38 Halo,
39 Bonds,
40 Labels,
41 Marks,
42 Overlay,
43}
44
45impl LayerName {
46 pub fn paint_order(self) -> u8 {
48 match self {
49 LayerName::Shading => 0,
50 LayerName::Halo => 1,
51 LayerName::Bonds => 2,
52 LayerName::Labels => 3,
53 LayerName::Marks => 4,
54 LayerName::Overlay => 5,
55 }
56 }
57}
58
59#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
65#[serde(rename_all = "snake_case")]
66#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
67#[cfg_attr(feature = "codegen", ts(export))]
68pub enum AromaticStyle {
69 #[default]
70 Circle,
71 Kekule,
72}
73
74#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
76#[serde(tag = "kind", rename_all = "lowercase")]
77#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
78#[cfg_attr(feature = "codegen", ts(export))]
79pub enum Primitive {
80 Path {
81 d: String,
82 #[serde(default, skip_serializing_if = "Option::is_none")]
83 #[cfg_attr(feature = "codegen", ts(optional))]
84 stroke: Option<String>,
85 #[serde(default, skip_serializing_if = "Option::is_none")]
86 #[cfg_attr(feature = "codegen", ts(optional))]
87 fill: Option<String>,
88 #[serde(default = "default_stroke_width")]
89 stroke_width: f64,
90 #[serde(default = "default_opacity")]
91 opacity: f64,
92 #[serde(default, skip_serializing_if = "Option::is_none")]
93 #[cfg_attr(feature = "codegen", ts(optional))]
94 stroke_dasharray: Option<String>,
95 #[serde(default, skip_serializing_if = "Option::is_none")]
96 #[cfg_attr(feature = "codegen", ts(optional))]
97 stroke_linecap: Option<String>,
98 #[serde(default, skip_serializing_if = "Option::is_none", rename = "cls")]
99 #[cfg_attr(feature = "codegen", ts(optional, rename = "cls"))]
100 class: Option<String>,
101 #[serde(default, skip_serializing_if = "Option::is_none")]
103 #[cfg_attr(feature = "codegen", ts(optional))]
104 data_text: Option<String>,
105 },
106 Circle {
107 cx: f64,
108 cy: f64,
109 r: f64,
110 #[serde(default, skip_serializing_if = "Option::is_none")]
111 #[cfg_attr(feature = "codegen", ts(optional))]
112 fill: Option<String>,
113 #[serde(default, skip_serializing_if = "Option::is_none")]
114 #[cfg_attr(feature = "codegen", ts(optional))]
115 stroke: Option<String>,
116 #[serde(default = "default_stroke_width")]
117 stroke_width: f64,
118 #[serde(default = "default_opacity")]
119 opacity: f64,
120 #[serde(default, skip_serializing_if = "Option::is_none", rename = "cls")]
121 #[cfg_attr(feature = "codegen", ts(optional, rename = "cls"))]
122 class: Option<String>,
123 },
124 Text {
127 x: f64,
128 y: f64,
129 text: String,
130 #[serde(default = "default_fill")]
131 fill: String,
132 #[serde(default = "default_font_size")]
133 font_size: f64,
134 #[serde(default = "default_anchor")]
135 anchor: TextAnchor,
136 #[serde(default, skip_serializing_if = "Option::is_none", rename = "cls")]
137 #[cfg_attr(feature = "codegen", ts(optional, rename = "cls"))]
138 class: Option<String>,
139 #[serde(default, skip_serializing_if = "Option::is_none")]
141 #[cfg_attr(feature = "codegen", ts(optional))]
142 rotate: Option<f64>,
143 },
144}
145
146fn default_stroke_width() -> f64 {
147 1.5
148}
149fn default_opacity() -> f64 {
150 1.0
151}
152fn default_fill() -> String {
153 "#000".into()
154}
155fn default_font_size() -> f64 {
156 12.0
157}
158fn default_anchor() -> TextAnchor {
159 TextAnchor::Middle
160}
161
162#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
163#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
164#[cfg_attr(feature = "codegen", ts(export))]
165pub struct Layer {
166 pub name: LayerName,
167 #[serde(default)]
168 pub primitives: Vec<Primitive>,
169}
170
171fn skip_zero(v: &f64) -> bool {
172 v.abs() < 1e-12
173}
174
175#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
182#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
183#[cfg_attr(feature = "codegen", ts(export))]
184pub struct Viewport {
185 #[serde(default, skip_serializing_if = "Option::is_none")]
186 #[cfg_attr(feature = "codegen", ts(optional))]
187 pub id: Option<String>,
188 #[serde(default)]
189 pub x: f64,
190 #[serde(default)]
191 pub y: f64,
192 #[serde(default, skip_serializing_if = "skip_zero")]
195 pub ox: f64,
196 #[serde(default, skip_serializing_if = "skip_zero")]
197 pub oy: f64,
198 pub width: f64,
199 pub height: f64,
200 #[serde(default)]
201 pub layers: Vec<Layer>,
202}
203
204impl Viewport {
205 pub fn local_origin(&self) -> (f64, f64) {
207 (self.x + self.ox, self.y + self.oy)
208 }
209
210 pub fn extend_layer(&mut self, name: LayerName, mut prims: Vec<Primitive>) {
212 if prims.is_empty() {
213 return;
214 }
215 if let Some(layer) = self.layers.iter_mut().find(|l| l.name == name) {
216 layer.primitives.append(&mut prims);
217 return;
218 }
219 self.layers.push(Layer {
220 name,
221 primitives: prims,
222 });
223 }
224
225 pub fn prepend_layer(&mut self, name: LayerName, mut prims: Vec<Primitive>) {
227 if prims.is_empty() {
228 return;
229 }
230 if let Some(layer) = self.layers.iter_mut().find(|l| l.name == name) {
231 prims.append(&mut layer.primitives);
232 layer.primitives = prims;
233 return;
234 }
235 self.layers.insert(
236 0,
237 Layer {
238 name,
239 primitives: prims,
240 },
241 );
242 }
243}
244
245#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
250#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
251#[cfg_attr(feature = "codegen", ts(export))]
252pub struct Scene {
253 pub width: f64,
254 pub height: f64,
255 #[serde(default, skip_serializing_if = "skip_zero")]
257 pub x: f64,
258 #[serde(default, skip_serializing_if = "skip_zero")]
260 pub y: f64,
261 pub viewports: Vec<Viewport>,
262 #[serde(default)]
264 pub overlays: Vec<Primitive>,
265 #[serde(default)]
268 pub halo: Vec<Primitive>,
269}
270
271#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
276#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
277#[cfg_attr(feature = "codegen", ts(export))]
278pub struct AtomIn {
279 pub index: i32,
280 #[serde(default, skip_serializing_if = "Option::is_none")]
281 #[cfg_attr(feature = "codegen", ts(optional))]
282 pub element: Option<String>,
283 #[serde(default, skip_serializing_if = "Option::is_none")]
285 #[cfg_attr(feature = "codegen", ts(optional))]
286 pub z: Option<u32>,
287 pub x: f64,
288 pub y: f64,
289 #[serde(default, skip_serializing_if = "Option::is_none")]
290 #[cfg_attr(feature = "codegen", ts(optional))]
291 pub label: Option<String>,
292 #[serde(default)]
293 pub charge: i32,
294 #[serde(default, skip_serializing_if = "Option::is_none")]
296 #[cfg_attr(feature = "codegen", ts(optional))]
297 pub mapno: Option<u32>,
298}
299
300impl AtomIn {
301 pub fn symbol(&self) -> &str {
303 if let Some(ref el) = self.element {
304 if !el.is_empty() {
305 return el.as_str();
306 }
307 }
308 match self.z {
309 Some(z) => crate::element_symbol(z),
310 None => "C",
311 }
312 }
313}
314
315#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
320#[serde(rename_all = "lowercase")]
321#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
322#[cfg_attr(feature = "codegen", ts(export))]
323pub enum Attach {
324 #[default]
326 Any,
327 All,
329}
330
331fn is_attach_any(a: &Attach) -> bool {
332 *a == Attach::Any
333}
334
335#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
341#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
342#[cfg_attr(feature = "codegen", ts(export))]
343pub struct SpokeIn {
344 #[serde(default, skip_serializing_if = "Option::is_none")]
346 #[cfg_attr(feature = "codegen", ts(optional))]
347 pub dummy: Option<i32>,
348 pub atom: i32,
350 pub endpts: Vec<i32>,
352 #[serde(default, skip_serializing_if = "is_attach_any")]
353 pub attach: Attach,
354}
355
356#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
358#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
359#[cfg_attr(feature = "codegen", ts(export))]
360pub struct BondIn {
361 pub index: i32,
362 pub begin: i32,
363 pub end: i32,
364 pub order: f64,
365 #[serde(default, skip_serializing_if = "Option::is_none")]
366 #[cfg_attr(feature = "codegen", ts(optional))]
367 pub stereo: Option<String>,
368 #[serde(default, skip_serializing_if = "Option::is_none")]
370 #[cfg_attr(feature = "codegen", ts(optional))]
371 pub interior: Option<(f64, f64)>,
372}
373
374#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
378#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
379#[cfg_attr(feature = "codegen", ts(export))]
380pub struct MoleculeIn {
381 #[serde(default, skip_serializing_if = "Option::is_none")]
382 #[cfg_attr(feature = "codegen", ts(optional))]
383 pub id: Option<String>,
384 pub atoms: Vec<AtomIn>,
385 pub bonds: Vec<BondIn>,
386 #[serde(default, skip_serializing_if = "Option::is_none")]
388 #[cfg_attr(feature = "codegen", ts(optional))]
389 pub color: Option<String>,
390 #[serde(default, skip_serializing_if = "Option::is_none")]
392 #[cfg_attr(feature = "codegen", ts(optional))]
393 pub atom_shade: Option<Vec<f64>>,
394 #[serde(default, skip_serializing_if = "Option::is_none")]
396 #[cfg_attr(feature = "codegen", ts(optional))]
397 pub bond_shade: Option<Vec<f64>>,
398 #[serde(default, skip_serializing_if = "Option::is_none")]
400 #[cfg_attr(feature = "codegen", ts(optional))]
401 pub shade_vmin: Option<f64>,
402 #[serde(default, skip_serializing_if = "Option::is_none")]
404 #[cfg_attr(feature = "codegen", ts(optional))]
405 pub shade_vmax: Option<f64>,
406 #[serde(
408 default = "default_mol_scale",
409 skip_serializing_if = "is_default_mol_scale"
410 )]
411 pub scale: f64,
412 #[serde(
415 default = "default_mol_weight",
416 skip_serializing_if = "is_default_mol_weight"
417 )]
418 pub weight: f64,
419 #[serde(default, skip_serializing_if = "is_default_aromatic")]
421 pub aromatic: AromaticStyle,
422 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
424 pub debug_box: bool,
425 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
427 pub debug_align: bool,
428 #[serde(default, skip_serializing_if = "Option::is_none")]
430 #[cfg_attr(feature = "codegen", ts(optional))]
431 pub align_debug: Option<AlignDebug>,
432 #[serde(default, skip_serializing_if = "Vec::is_empty")]
434 pub spokes: Vec<SpokeIn>,
435}
436
437#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
439#[serde(rename_all = "snake_case")]
440#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
441#[cfg_attr(feature = "codegen", ts(export))]
442pub enum AlignDebugRole {
443 Template,
444 Query,
445}
446
447#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
449#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
450#[cfg_attr(feature = "codegen", ts(export))]
451pub struct AlignDebug {
452 pub role: AlignDebugRole,
453 #[serde(default, skip_serializing_if = "Option::is_none")]
455 #[cfg_attr(feature = "codegen", ts(optional))]
456 pub peer_id: Option<String>,
457 #[serde(default)]
459 pub tags: Vec<(i32, i32)>,
460}
461
462fn default_mol_scale() -> f64 {
463 1.0
464}
465
466fn is_default_mol_scale(s: &f64) -> bool {
467 (*s - 1.0).abs() < 1e-12
468}
469
470fn default_mol_weight() -> f64 {
471 1.0
472}
473
474fn is_default_mol_weight(s: &f64) -> bool {
475 (*s - 1.0).abs() < 1e-12
476}
477
478fn is_default_aromatic(s: &AromaticStyle) -> bool {
479 *s == AromaticStyle::Circle
480}
481
482impl Default for MoleculeIn {
483 fn default() -> Self {
484 Self {
485 id: None,
486 atoms: Vec::new(),
487 bonds: Vec::new(),
488 color: None,
489 atom_shade: None,
490 bond_shade: None,
491 shade_vmin: None,
492 shade_vmax: None,
493 scale: 1.0,
494 weight: 1.0,
495 aromatic: AromaticStyle::default(),
496 debug_box: false,
497 debug_align: false,
498 align_debug: None,
499 spokes: Vec::new(),
500 }
501 }
502}
503
504impl MoleculeIn {
505 pub fn diagram_scale(&self) -> f64 {
507 if self.scale > 0.0 && self.scale.is_finite() {
508 self.scale
509 } else {
510 1.0
511 }
512 }
513
514 pub fn diagram_weight(&self) -> f64 {
519 crate::metrics::diagram_weight(self.weight)
520 }
521
522 pub fn atom(&self, idx: i32) -> Option<&AtomIn> {
524 self.atoms
525 .iter()
526 .find(|a| a.index == idx)
527 .or_else(|| self.atoms.get(idx as usize))
528 }
529
530 pub fn centroid_of(&self, endpts: &[i32]) -> Option<(f64, f64)> {
532 if endpts.is_empty() {
533 return None;
534 }
535 let mut sx = 0.0;
536 let mut sy = 0.0;
537 let mut n = 0usize;
538 for &i in endpts {
539 let Some(a) = self.atom(i) else {
540 continue;
541 };
542 sx += a.x;
543 sy += a.y;
544 n += 1;
545 }
546 (n > 0).then_some((sx / n as f64, sy / n as f64))
547 }
548}
549
550pub fn scale_path_d(d: &str, s: f64) -> String {
552 if (s - 1.0).abs() < 1e-12 || d.is_empty() {
553 return d.to_string();
554 }
555 let bytes = d.as_bytes();
556 let mut out = String::with_capacity(d.len());
557 let mut i = 0;
558 while i < bytes.len() {
559 let c = bytes[i] as char;
560 if c == '-' || c == '+' || c == '.' || c.is_ascii_digit() {
561 let start = i;
562 if c == '-' || c == '+' {
563 i += 1;
564 }
565 while i < bytes.len() && (bytes[i] as char).is_ascii_digit() {
566 i += 1;
567 }
568 if i < bytes.len() && bytes[i] == b'.' {
569 i += 1;
570 while i < bytes.len() && (bytes[i] as char).is_ascii_digit() {
571 i += 1;
572 }
573 }
574 if i < bytes.len() && (bytes[i] == b'e' || bytes[i] == b'E') {
575 i += 1;
576 if i < bytes.len() && (bytes[i] == b'-' || bytes[i] == b'+') {
577 i += 1;
578 }
579 while i < bytes.len() && (bytes[i] as char).is_ascii_digit() {
580 i += 1;
581 }
582 }
583 let raw = std::str::from_utf8(&bytes[start..i]).unwrap_or("0");
584 let num: f64 = raw.parse().unwrap_or(0.0);
585 out.push_str(&format!("{:.2}", num * s));
586 } else {
587 out.push(c);
588 i += 1;
589 }
590 }
591 out
592}
593
594fn scale_dasharray(dash: &str, s: f64) -> String {
595 if (s - 1.0).abs() < 1e-12 {
596 return dash.to_string();
597 }
598 dash.split(|c: char| c == ',' || c.is_whitespace())
599 .filter(|t| !t.is_empty())
600 .map(|t| {
601 t.parse::<f64>()
602 .map(|n| format!("{:.2}", n * s))
603 .unwrap_or_else(|_| t.to_string())
604 })
605 .collect::<Vec<_>>()
606 .join(" ")
607}
608
609impl Primitive {
610 pub fn scale_uniform(&self, s: f64) -> Self {
612 if (s - 1.0).abs() < 1e-12 {
613 return self.clone();
614 }
615 match self {
616 Primitive::Path {
617 d,
618 stroke,
619 fill,
620 stroke_width,
621 opacity,
622 stroke_dasharray,
623 stroke_linecap,
624 class,
625 data_text,
626 } => Primitive::Path {
627 d: scale_path_d(d, s),
628 stroke: stroke.clone(),
629 fill: fill.clone(),
630 stroke_width: *stroke_width * s,
631 opacity: *opacity,
632 stroke_dasharray: stroke_dasharray.as_ref().map(|d| scale_dasharray(d, s)),
633 stroke_linecap: stroke_linecap.clone(),
634 class: class.clone(),
635 data_text: data_text.clone(),
636 },
637 Primitive::Circle {
638 cx,
639 cy,
640 r,
641 fill,
642 stroke,
643 stroke_width,
644 opacity,
645 class,
646 } => Primitive::Circle {
647 cx: *cx * s,
648 cy: *cy * s,
649 r: *r * s,
650 fill: fill.clone(),
651 stroke: stroke.clone(),
652 stroke_width: *stroke_width * s,
653 opacity: *opacity,
654 class: class.clone(),
655 },
656 Primitive::Text {
657 x,
658 y,
659 text,
660 fill,
661 font_size,
662 anchor,
663 class,
664 rotate,
665 } => Primitive::Text {
666 x: *x * s,
667 y: *y * s,
668 text: text.clone(),
669 fill: fill.clone(),
670 font_size: *font_size * s,
671 anchor: *anchor,
672 class: class.clone(),
673 rotate: *rotate,
674 },
675 }
676 }
677}
678
679impl Viewport {
680 pub fn scale_uniform(&self, s: f64) -> Self {
681 if (s - 1.0).abs() < 1e-12 {
682 return self.clone();
683 }
684 Self {
685 id: self.id.clone(),
686 x: self.x * s,
687 y: self.y * s,
688 ox: self.ox * s,
689 oy: self.oy * s,
690 width: self.width * s,
691 height: self.height * s,
692 layers: self
693 .layers
694 .iter()
695 .map(|layer| Layer {
696 name: layer.name,
697 primitives: layer
698 .primitives
699 .iter()
700 .map(|p| p.scale_uniform(s))
701 .collect(),
702 })
703 .collect(),
704 }
705 }
706}
707
708impl Scene {
709 pub fn empty(width: f64, height: f64) -> Self {
710 Self {
711 width,
712 height,
713 x: 0.0,
714 y: 0.0,
715 viewports: Vec::new(),
716 overlays: Vec::new(),
717 halo: Vec::new(),
718 }
719 }
720
721 pub fn scale_uniform(&self, s: f64) -> Self {
723 if (s - 1.0).abs() < 1e-12 {
724 return self.clone();
725 }
726 Self {
727 width: self.width * s,
728 height: self.height * s,
729 x: self.x * s,
730 y: self.y * s,
731 viewports: self
732 .viewports
733 .iter()
734 .map(|vp| vp.scale_uniform(s))
735 .collect(),
736 overlays: self.overlays.iter().map(|p| p.scale_uniform(s)).collect(),
737 halo: self.halo.iter().map(|p| p.scale_uniform(s)).collect(),
738 }
739 }
740}
741
742#[cfg(test)]
743mod tests {
744 use super::*;
745
746 #[test]
747 fn scene_json_roundtrip_minimal() {
748 let scene = Scene {
749 width: 70.0,
750 height: 75.0,
751 x: 0.0,
752 y: 0.0,
753 viewports: vec![Viewport {
754 id: Some("m0".into()),
755 x: 0.0,
756 y: 0.0,
757 ox: 0.0,
758 oy: 0.0,
759 width: 70.0,
760 height: 75.0,
761 layers: vec![Layer {
762 name: LayerName::Bonds,
763 primitives: vec![Primitive::Path {
764 d: "M 0 0 L 20 0".into(),
765 stroke: Some("#111".into()),
766 fill: Some("none".into()),
767 stroke_width: 0.84,
768 opacity: 1.0,
769 stroke_dasharray: None,
770 stroke_linecap: Some("round".into()),
771 class: Some("bond bond-skeleton".into()),
772 data_text: None,
773 }],
774 }],
775 }],
776 overlays: vec![],
777 halo: vec![],
778 };
779 let json = serde_json::to_string(&scene).expect("serialize");
780 let back: Scene = serde_json::from_str(&json).expect("deserialize");
781 assert_eq!(back.width, 70.0);
782 assert_eq!(back.viewports[0].layers[0].primitives.len(), 1);
783 }
784
785 #[test]
786 fn primitive_defaults_via_partial_json() {
787 let path: Primitive = serde_json::from_str(r#"{"kind":"path","d":"M 0 0 L 1 0"}"#).unwrap();
789 match path {
790 Primitive::Path {
791 stroke_width,
792 opacity,
793 ..
794 } => {
795 assert!((stroke_width - 1.5).abs() < 1e-12);
796 assert!((opacity - 1.0).abs() < 1e-12);
797 }
798 _ => panic!("expected path"),
799 }
800 let circle: Primitive =
801 serde_json::from_str(r#"{"kind":"circle","cx":0,"cy":0,"r":1}"#).unwrap();
802 match circle {
803 Primitive::Circle {
804 stroke_width,
805 opacity,
806 ..
807 } => {
808 assert!((stroke_width - 1.5).abs() < 1e-12);
809 assert!((opacity - 1.0).abs() < 1e-12);
810 }
811 _ => panic!("expected circle"),
812 }
813 let text: Primitive =
814 serde_json::from_str(r#"{"kind":"text","x":0,"y":0,"text":"C"}"#).unwrap();
815 match text {
816 Primitive::Text {
817 fill,
818 font_size,
819 anchor,
820 ..
821 } => {
822 assert_eq!(fill, "#000");
823 assert!((font_size - 12.0).abs() < 1e-12);
824 assert_eq!(anchor, TextAnchor::Middle);
825 }
826 _ => panic!("expected text"),
827 }
828 }
829
830 #[test]
831 fn atom_symbol_resolves_element_z_and_fallback() {
832 let with_el = AtomIn {
833 index: 0,
834 element: Some("N".into()),
835 z: Some(6),
836 x: 0.0,
837 y: 0.0,
838 label: None,
839 charge: 0,
840 mapno: None,
841 };
842 assert_eq!(with_el.symbol(), "N");
843
844 let empty_el = AtomIn {
845 index: 1,
846 element: Some(String::new()),
847 z: Some(8),
848 x: 0.0,
849 y: 0.0,
850 label: None,
851 charge: 0,
852 mapno: None,
853 };
854 assert_eq!(empty_el.symbol(), "O");
855
856 let z_only = AtomIn {
857 index: 2,
858 element: None,
859 z: Some(7),
860 x: 0.0,
861 y: 0.0,
862 label: None,
863 charge: 0,
864 mapno: None,
865 };
866 assert_eq!(z_only.symbol(), "N");
867
868 let bare = AtomIn {
869 index: 3,
870 element: None,
871 z: None,
872 x: 0.0,
873 y: 0.0,
874 label: None,
875 charge: 0,
876 mapno: None,
877 };
878 assert_eq!(bare.symbol(), "C");
879 }
880
881 #[test]
882 fn scene_empty_has_no_viewports() {
883 let s = Scene::empty(100.0, 80.0);
884 assert_eq!(s.width, 100.0);
885 assert_eq!(s.height, 80.0);
886 assert!(s.viewports.is_empty());
887 assert!(s.overlays.is_empty());
888 assert!(s.halo.is_empty());
889 }
890
891 #[test]
892 fn mol_scale_weight_defaults_and_fallbacks() {
893 let mol: MoleculeIn = serde_json::from_str(r#"{"id":"m","atoms":[],"bonds":[]}"#).unwrap();
895 assert!((mol.scale - 1.0).abs() < 1e-12);
896 assert!((mol.weight - 1.0).abs() < 1e-12);
897 assert!((mol.diagram_scale() - 1.0).abs() < 1e-12);
898 assert!((mol.diagram_weight() - crate::metrics::WEIGHT_AT_ONE).abs() < 1e-12);
899
900 let mut bad = mol.clone();
901 bad.scale = 0.0;
902 assert!((bad.diagram_scale() - 1.0).abs() < 1e-12);
903 bad.scale = f64::NAN;
904 assert!((bad.diagram_scale() - 1.0).abs() < 1e-12);
905 bad.scale = -2.0;
906 assert!((bad.diagram_scale() - 1.0).abs() < 1e-12);
907 bad.scale = 1.5;
908 assert!((bad.diagram_scale() - 1.5).abs() < 1e-12);
909
910 let json_default = serde_json::to_value(&mol).unwrap();
912 assert!(json_default.get("scale").is_none());
913 assert!(json_default.get("weight").is_none());
914 let mut thick = mol;
915 thick.weight = 2.0;
916 thick.scale = 1.5;
917 let json_thick = serde_json::to_value(&thick).unwrap();
918 assert_eq!(json_thick["weight"], 2.0);
919 assert_eq!(json_thick["scale"], 1.5);
920 }
921
922 #[test]
923 fn scale_path_d_and_dasharray_cover_token_shapes() {
924 assert_eq!(scale_path_d("M 0 0", 1.0), "M 0 0");
925 assert_eq!(scale_path_d("", 2.0), "");
926 let d = scale_path_d("M -1.5e1 +2.0E+1 L 3 4Z", 2.0);
928 assert!(d.contains("-30.00") || d.contains("-30"), "{d}");
929 assert!(d.contains("40.00") || d.contains("40"), "{d}");
930 assert!(d.ends_with('Z') || d.contains('Z'), "{d}");
931
932 assert_eq!(scale_dasharray("1 2", 1.0), "1 2");
933 assert_eq!(scale_dasharray("1,2 3", 2.0), "2.00 4.00 6.00");
934 assert_eq!(scale_dasharray("1 foo", 2.0), "2.00 foo");
936 }
937
938 #[test]
939 fn scale_uniform_covers_path_circle_text_and_identity() {
940 let path = Primitive::Path {
941 d: "M 10 0 L 20 0".into(),
942 stroke: Some("#111".into()),
943 fill: Some("none".into()),
944 stroke_width: 1.0,
945 opacity: 1.0,
946 stroke_dasharray: Some("2 1".into()),
947 stroke_linecap: Some("round".into()),
948 class: Some("bond".into()),
949 data_text: None,
950 };
951 let circle = Primitive::Circle {
952 cx: 5.0,
953 cy: 6.0,
954 r: 2.0,
955 fill: None,
956 stroke: Some("#f00".into()),
957 stroke_width: 0.5,
958 opacity: 0.7,
959 class: Some("mark".into()),
960 };
961 let text = Primitive::Text {
962 x: 1.0,
963 y: 2.0,
964 text: "C".into(),
965 fill: "#000".into(),
966 font_size: 12.0,
967 anchor: TextAnchor::Middle,
968 class: None,
969 rotate: None,
970 };
971
972 assert_eq!(path.scale_uniform(1.0), path);
974 assert_eq!(circle.scale_uniform(1.0), circle);
975 assert_eq!(text.scale_uniform(1.0), text);
976
977 match path.scale_uniform(2.0) {
978 Primitive::Path {
979 d,
980 stroke_width,
981 stroke_dasharray,
982 ..
983 } => {
984 assert!(d.contains("20.00") && d.contains("40.00"), "{d}");
985 assert!((stroke_width - 2.0).abs() < 1e-12);
986 assert_eq!(stroke_dasharray.as_deref(), Some("4.00 2.00"));
987 }
988 _ => panic!("path"),
989 }
990 match circle.scale_uniform(2.0) {
991 Primitive::Circle {
992 cx,
993 cy,
994 r,
995 stroke_width,
996 ..
997 } => {
998 assert!((cx - 10.0).abs() < 1e-12);
999 assert!((cy - 12.0).abs() < 1e-12);
1000 assert!((r - 4.0).abs() < 1e-12);
1001 assert!((stroke_width - 1.0).abs() < 1e-12);
1002 }
1003 _ => panic!("circle"),
1004 }
1005 match text.scale_uniform(2.0) {
1006 Primitive::Text {
1007 x, y, font_size, ..
1008 } => {
1009 assert!((x - 2.0).abs() < 1e-12);
1010 assert!((y - 4.0).abs() < 1e-12);
1011 assert!((font_size - 24.0).abs() < 1e-12);
1012 }
1013 _ => panic!("text"),
1014 }
1015
1016 let vp = Viewport {
1017 id: Some("m0".into()),
1018 x: 1.0,
1019 y: 2.0,
1020 ox: 0.0,
1021 oy: 0.0,
1022 width: 10.0,
1023 height: 20.0,
1024 layers: vec![Layer {
1025 name: LayerName::Marks,
1026 primitives: vec![circle.clone()],
1027 }],
1028 };
1029 assert_eq!(vp.scale_uniform(1.0), vp);
1030 let vp2 = vp.scale_uniform(2.0);
1031 assert!((vp2.x - 2.0).abs() < 1e-12);
1032 assert!((vp2.width - 20.0).abs() < 1e-12);
1033
1034 let scene = Scene {
1035 width: 10.0,
1036 height: 20.0,
1037 x: 1.0,
1038 y: 2.0,
1039 viewports: vec![vp],
1040 overlays: vec![text],
1041 halo: vec![path],
1042 };
1043 assert_eq!(scene.scale_uniform(1.0), scene);
1044 let s2 = scene.scale_uniform(2.0);
1045 assert!((s2.width - 20.0).abs() < 1e-12);
1046 assert!((s2.height - 40.0).abs() < 1e-12);
1047 assert_eq!(s2.overlays.len(), 1);
1048 assert_eq!(s2.halo.len(), 1);
1049 assert!((s2.x - 2.0).abs() < 1e-12);
1050 assert!((s2.y - 4.0).abs() < 1e-12);
1051 }
1052}