Skip to main content

xpict_core/
scene.rs

1//! Drawable scene document — engine-neutral primitives shared by Python & JS.
2//!
3//! One molecule → one [`Viewport`] inside a [`Scene`]. Circle overlays and shade
4//! disks are layers on that viewport. Multi-mol / ELK schemes compose several
5//! viewports into one scene.
6//!
7//! 1. [`crate::doc::render`] supplies coords + chem metadata (CoordGen + align).
8//! 2. Rust builds a [`Scene`] of typed primitives (paths, circles, …).
9//! 3. [`crate::scene_to_svg`] emits SVG; hosts only wrap (IPython / `<img>`).
10
11use serde::{Deserialize, Serialize};
12
13#[cfg(feature = "codegen")]
14use schemars::JsonSchema;
15#[cfg(feature = "codegen")]
16use ts_rs::TS;
17
18/// Horizontal text anchor (SVG `text-anchor`).
19#[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/// Layer name inside a molecule viewport.
30///
31/// Paint order is the nesting order inside `g.xpict-mol` (bottom → top).
32#[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    /// Bottom → top inside one mol group (shading under halo under chem).
47    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/// How fully aromatic rings are drawn.
60///
61/// ``circle`` (default): skeleton singles + stroked ring circle for CTAB ``4`` /
62/// RDKit ``1.5`` rings. ``kekule``: alternating double/single strokes for paint
63/// only (stored bond orders on the molecule are unchanged).
64#[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/// One drawable primitive in SVG space (+Y down).
75#[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        /// Plain label string for ``data-text`` (glyph paths only).
102        #[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    /// Logical text; serializers outline to glyph paths (Liberation) or emit
125    /// `<text>` when the host prefers.
126    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        /// Degrees about the glyph center `(x, y)`. Omit when upright.
140        #[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/// One molecule viewport in a diagram (after ELK/grid placement).
176///
177/// `x`/`y` are the mol group's placement in the parent. `ox`/`oy` are the
178/// leftover fit origin of local primitive coords. SVG is
179/// `translate(x,y) translate(ox,oy)` around nested layer groups — primitives
180/// stay in paint space; the group carries the transform.
181#[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    /// Local leftover origin (fit). Nested inside the mol group, not baked
193    /// into path `d`.
194    #[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    /// Document-space origin of this mol's local primitive coords.
206    pub fn local_origin(&self) -> (f64, f64) {
207        (self.x + self.ox, self.y + self.oy)
208    }
209
210    /// Append primitives to the named layer, creating it if needed.
211    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    /// Put primitives under existing ink of the named layer (regions under shade).
226    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/// Full drawable document before SVG/HTML serialization.
246///
247/// Python `contracts.scene.Scene` and JS consumers should mirror this shape
248/// (JSON round-trip is the ABI).
249#[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    /// viewBox min-x. Size is [`Self::width`] × [`Self::height`]. Default 0.
256    #[serde(default, skip_serializing_if = "skip_zero")]
257    pub x: f64,
258    /// viewBox min-y. Default 0.
259    #[serde(default, skip_serializing_if = "skip_zero")]
260    pub y: f64,
261    pub viewports: Vec<Viewport>,
262    /// Document-space primitives (reaction arrows) above viewports.
263    #[serde(default)]
264    pub overlays: Vec<Primitive>,
265    /// Document-space knockout (scheme compose). Per-mol halo lives in the
266    /// viewport `Halo` layer so it nests inside `g.xpict-mol`.
267    #[serde(default)]
268    pub halo: Vec<Primitive>,
269}
270
271/// Atom input for a molecule depict call (SVG-space coords from the caller).
272///
273/// Identity: pass ``element`` and/or atomic number ``z``. If only ``z`` is
274/// set, the symbol comes from [`crate::element_symbol`].
275#[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    /// Atomic number (`0` = ``*``). Used when ``element`` is omitted.
284    #[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    /// Reaction / SMILES atom-map number (`:n` in brackets), when known.
295    #[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    /// Resolved element symbol (`element` if set, else from ``z``, else ``"C"``).
302    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/// How a ring-center stem attaches to its [`SpokeIn::endpts`].
316///
317/// CXSMILES ``m:`` is variable attachment ([`Attach::Any`]). Haptic / ALL is
318/// reserved for a later ``C:`` / MOL ENDPTS path.
319#[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    /// One of the endpoints (Markush / variable attachment).
325    #[default]
326    Any,
327    /// All endpoints at once (haptic multicenter).
328    All,
329}
330
331fn is_attach_any(a: &Attach) -> bool {
332    *a == Attach::Any
333}
334
335/// Segment drawn from a ring centroid to a substituent (CX ``m:``).
336///
337/// The SMILES dummy ``*`` is **not** a neighbor in the spoke graph (it is a
338/// silent paint handle at the centroid). [`Self::atom`] is the first real atom
339/// of the substituent.
340#[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    /// Silent centroid atom (original CX dummy index), or omitted when dropped.
345    #[serde(default, skip_serializing_if = "Option::is_none")]
346    #[cfg_attr(feature = "codegen", ts(optional))]
347    pub dummy: Option<i32>,
348    /// First real atom of the substituent (stem end).
349    pub atom: i32,
350    /// Ring atoms the stem represents (CX ``m:dummy:a.b.c``).
351    pub endpts: Vec<i32>,
352    #[serde(default, skip_serializing_if = "is_attach_any")]
353    pub attach: Attach,
354}
355
356/// Bond input (indices into [`AtomIn::index`]).
357#[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    /// Unit normal toward ring interior (ring doubles); omit for centered.
369    #[serde(default, skip_serializing_if = "Option::is_none")]
370    #[cfg_attr(feature = "codegen", ts(optional))]
371    pub interior: Option<(f64, f64)>,
372}
373
374/// One molecule ready to paint (coords already in SVG / ``SCALE`` space).
375///
376/// Publication circles live on the document ``MolNode.circle`` overlay, not here.
377#[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    /// Ink color for backbone bonds and atom labels (CSS). Default ``#111``.
387    #[serde(default, skip_serializing_if = "Option::is_none")]
388    #[cfg_attr(feature = "codegen", ts(optional))]
389    pub color: Option<String>,
390    /// Per-atom shade scores (same order as [`Self::atoms`]); omit if unshaded.
391    #[serde(default, skip_serializing_if = "Option::is_none")]
392    #[cfg_attr(feature = "codegen", ts(optional))]
393    pub atom_shade: Option<Vec<f64>>,
394    /// Per-bond shade scores (same order as [`Self::bonds`]).
395    #[serde(default, skip_serializing_if = "Option::is_none")]
396    #[cfg_attr(feature = "codegen", ts(optional))]
397    pub bond_shade: Option<Vec<f64>>,
398    /// Shade colormap window low (default ``0``). Not inferred from data.
399    #[serde(default, skip_serializing_if = "Option::is_none")]
400    #[cfg_attr(feature = "codegen", ts(optional))]
401    pub shade_vmin: Option<f64>,
402    /// Shade colormap window high (default ``1``). Not inferred from data.
403    #[serde(default, skip_serializing_if = "Option::is_none")]
404    #[cfg_attr(feature = "codegen", ts(optional))]
405    pub shade_vmax: Option<f64>,
406    /// Uniform diagram scale (font, stroke, pad, geometry). ``1.0`` = house size.
407    #[serde(
408        default = "default_mol_scale",
409        skip_serializing_if = "is_default_mol_scale"
410    )]
411    pub scale: f64,
412    /// Ink weight for backbone stroke and label glyph thicken. ``1.0`` = house;
413    /// may go down to ~``2/3`` (Regular stem); typical thicken up to ~2.
414    #[serde(
415        default = "default_mol_weight",
416        skip_serializing_if = "is_default_mol_weight"
417    )]
418    pub weight: f64,
419    /// Aromatic ring paint: circle (default) or Kekulé doubles.
420    #[serde(default, skip_serializing_if = "is_default_aromatic")]
421    pub aromatic: AromaticStyle,
422    /// When true, paint dashed debug rectangles for label / mol / scene boxes.
423    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
424    pub debug_box: bool,
425    /// When true, paint alignment correspondence overlays (needs [`Self::align_debug`]).
426    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
427    pub debug_align: bool,
428    /// Stamped match tags from the host/core align step (not cascading).
429    #[serde(default, skip_serializing_if = "Option::is_none")]
430    #[cfg_attr(feature = "codegen", ts(optional))]
431    pub align_debug: Option<AlignDebug>,
432    /// Ring-center stems (CX ``m:``). Empty when the mol has none.
433    #[serde(default, skip_serializing_if = "Vec::is_empty")]
434    pub spokes: Vec<SpokeIn>,
435}
436
437/// Role of a molecule in an alignment debug overlay.
438#[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/// Stamped alignment correspondence for [`MoleculeIn::debug_align`] paint.
448#[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    /// Peer mol id(s): template lists queries; query names its template.
454    #[serde(default, skip_serializing_if = "Option::is_none")]
455    #[cfg_attr(feature = "codegen", ts(optional))]
456    pub peer_id: Option<String>,
457    /// `(atom_index_on_this_mol, tag)` — tag is the **template atom index**.
458    #[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    /// Effective diagram scale; non-positive values fall back to ``1.0``.
506    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    /// Absolute ink multiplier for this mol (user ``weight`` × house base).
515    ///
516    /// # Panics
517    /// Panics if [`Self::weight`] is invalid (see [`crate::metrics::diagram_weight`]).
518    pub fn diagram_weight(&self) -> f64 {
519        crate::metrics::diagram_weight(self.weight)
520    }
521
522    /// Atom with [`AtomIn::index`] ``idx``.
523    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    /// Mean of ``endpts`` coordinates (ring-center for a spoke).
531    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
550/// Multiply every numeric token in an SVG path ``d`` (M/L/Z polygons).
551pub 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    /// Uniform scale about the origin (stroke widths and path coords).
611    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    /// Scale the whole diagram about the origin (equiv. to scaled font_px / metrics).
722    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        // serde default fns (stroke_width / opacity / fill / font_size / anchor).
788        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        // Omitted fields → serde defaults (covers default_mol_weight / scale).
894        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        // skip_serializing_if: defaults omitted; non-defaults kept.
911        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        // Signed ints, decimals, scientific notation.
927        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        // Non-numeric token preserved.
935        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        // Identity early-outs.
973        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}