Skip to main content

xpict_core/doc/
chrome.rs

1//! Mol chrome wire types (ABI A) and internal Annotation IR (B).
2//!
3//! Wire fields live on [`super::MolNode`]. Paint consumes
4//! [`annotations_from_mol`]. A↔B round-trips are Rust-only (not codegen).
5
6use std::collections::BTreeMap;
7
8use serde::{Deserialize, Serialize};
9
10#[cfg(feature = "codegen")]
11use schemars::JsonSchema;
12#[cfg(feature = "codegen")]
13use ts_rs::TS;
14
15use super::spec::{LabelPos, ShadeSpec};
16
17// ---------------------------------------------------------------------------
18// Shared ink / text (wire + IR)
19// ---------------------------------------------------------------------------
20
21/// Caption / label content: bare string or styled object.
22#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
23#[serde(untagged)]
24#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
25#[cfg_attr(feature = "codegen", ts(export))]
26pub enum MolText {
27    /// Plain string (default placement depends on consumer: mol name → below).
28    Plain(String),
29    /// Explicit content + optional style / side.
30    Styled(MolTextSpec),
31}
32
33impl MolText {
34    pub fn content(&self) -> &str {
35        match self {
36            MolText::Plain(s) => s.as_str(),
37            MolText::Styled(t) => t.content.as_str(),
38        }
39    }
40
41    pub fn as_styled(&self) -> MolTextSpec {
42        match self {
43            MolText::Plain(s) => MolTextSpec {
44                content: s.clone(),
45                ..MolTextSpec::default()
46            },
47            MolText::Styled(t) => t.clone(),
48        }
49    }
50}
51
52/// Expanded text content for mol name, region labels, callouts, atom labels.
53#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
54#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
55#[cfg_attr(feature = "codegen", ts(export))]
56pub struct MolTextSpec {
57    /// Display string — chem label markup (`$R_1$`, `N^+`, `**bold**`, …).
58    #[serde(default)]
59    pub content: String,
60    /// Side relative to the anchor (mol name / outside region label).
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    #[cfg_attr(feature = "codegen", ts(optional))]
63    pub pos: Option<LabelPos>,
64    /// Font scale relative to house atom-label size (mol `name` defaults to 1.5×).
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    #[cfg_attr(feature = "codegen", ts(optional))]
67    pub scale: Option<f64>,
68    /// CSS color.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    #[cfg_attr(feature = "codegen", ts(optional))]
71    pub color: Option<String>,
72    /// Region label: inside the hull or outside (default outside).
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    #[cfg_attr(feature = "codegen", ts(optional))]
75    pub place: Option<RegionTextPlace>,
76    /// Gap (px) between mol ink AABB and this caption (snug, no clash).
77    /// Omit → house default (see caption paint `CAPTION_MARGIN_DEFAULT`).
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    #[cfg_attr(feature = "codegen", ts(optional))]
80    pub margin: Option<f64>,
81}
82
83/// Where a region caption sits relative to the region geometry.
84#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
85#[serde(rename_all = "snake_case")]
86#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
87#[cfg_attr(feature = "codegen", ts(export))]
88pub enum RegionTextPlace {
89    #[default]
90    Outside,
91    Inside,
92}
93
94/// Fill ink for region / circle.
95#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
96#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
97#[cfg_attr(feature = "codegen", ts(export))]
98pub struct FillSpec {
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    #[cfg_attr(feature = "codegen", ts(optional))]
101    pub color: Option<String>,
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    #[cfg_attr(feature = "codegen", ts(optional))]
104    pub opacity: Option<f64>,
105}
106
107/// Stroke ink for region / circle.
108///
109/// Omit / `null` with a fill → no stroke. Omit / `null` without fill → house
110/// outline. Set `color: "none"` (or `width: 0`) to force no stroke; set a
111/// [`StrokeSpec`] object to force an outline even when filled.
112#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
113#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
114#[cfg_attr(feature = "codegen", ts(export))]
115pub struct StrokeSpec {
116    /// CSS color, or `"none"` to disable stroke.
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    #[cfg_attr(feature = "codegen", ts(optional))]
119    pub color: Option<String>,
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    #[cfg_attr(feature = "codegen", ts(optional))]
122    pub width: Option<f64>,
123    /// `solid` | `dashed` | `dotted` or a raw SVG dasharray.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    #[cfg_attr(feature = "codegen", ts(optional))]
126    pub dash: Option<String>,
127}
128
129/// Region hull style (not wire `circle` highlights).
130#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
131#[serde(rename_all = "snake_case")]
132#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
133#[cfg_attr(feature = "codegen", ts(export))]
134pub enum RegionStyle {
135    #[default]
136    Box,
137    /// Circular region hull (distinct from highlight [`CircleSpec`]).
138    Circle,
139    Bezier,
140}
141
142/// One region highlight on a mol.
143#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
144#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
145#[cfg_attr(feature = "codegen", ts(export))]
146pub struct RegionSpec {
147    #[serde(default)]
148    pub style: RegionStyle,
149    /// Atom indices that must lie inside the region.
150    #[serde(default)]
151    pub atoms: Vec<u32>,
152    /// Atom indices that must stay outside.
153    #[serde(default, skip_serializing_if = "Vec::is_empty")]
154    pub exclude: Vec<u32>,
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    #[cfg_attr(feature = "codegen", ts(optional))]
157    pub fill: Option<FillSpec>,
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    #[cfg_attr(feature = "codegen", ts(optional))]
160    pub stroke: Option<StrokeSpec>,
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    #[cfg_attr(feature = "codegen", ts(optional))]
163    pub text: Option<MolText>,
164    /// Optional z-order override (lower = further back). Default band: region base.
165    #[serde(default, skip_serializing_if = "Option::is_none")]
166    #[cfg_attr(feature = "codegen", ts(optional))]
167    pub z: Option<i32>,
168}
169
170/// One-or-many regions on the wire.
171#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
172#[serde(untagged)]
173#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
174#[cfg_attr(feature = "codegen", ts(export))]
175pub enum RegionField {
176    One(RegionSpec),
177    Many(Vec<RegionSpec>),
178}
179
180impl RegionField {
181    pub fn iter(&self) -> impl Iterator<Item = &RegionSpec> {
182        match self {
183            RegionField::One(r) => std::slice::from_ref(r).iter(),
184            RegionField::Many(v) => v.iter(),
185        }
186    }
187
188    pub fn into_vec(self) -> Vec<RegionSpec> {
189        match self {
190            RegionField::One(r) => vec![r],
191            RegionField::Many(v) => v,
192        }
193    }
194}
195
196/// Atom, bond, or ring highlight.
197#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
198#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
199#[cfg_attr(feature = "codegen", ts(export))]
200pub struct CircleSpec {
201    /// One circle centered on each atom index.
202    #[serde(default, skip_serializing_if = "Vec::is_empty")]
203    pub atoms: Vec<u32>,
204    /// Bond endpoint pairs — one circle at each bond midpoint (`[begin, end]`, order-insensitive).
205    #[serde(default, skip_serializing_if = "Vec::is_empty")]
206    pub bonds: Vec<(u32, u32)>,
207    /// Ordered ring atoms — one circle at the ring centroid (aromatic-style).
208    #[serde(default, skip_serializing_if = "Option::is_none")]
209    #[cfg_attr(feature = "codegen", ts(optional))]
210    pub ring: Option<Vec<u32>>,
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    #[cfg_attr(feature = "codegen", ts(optional))]
213    pub fill: Option<FillSpec>,
214    #[serde(default, skip_serializing_if = "Option::is_none")]
215    #[cfg_attr(feature = "codegen", ts(optional))]
216    pub stroke: Option<StrokeSpec>,
217    /// Radius scale vs house default.
218    #[serde(default, skip_serializing_if = "Option::is_none")]
219    #[cfg_attr(feature = "codegen", ts(optional))]
220    pub scale: Option<f64>,
221    #[serde(default, skip_serializing_if = "Option::is_none")]
222    #[cfg_attr(feature = "codegen", ts(optional))]
223    pub z: Option<i32>,
224}
225
226#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
227#[serde(untagged)]
228#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
229#[cfg_attr(feature = "codegen", ts(export))]
230pub enum CircleField {
231    One(CircleSpec),
232    Many(Vec<CircleSpec>),
233}
234
235impl CircleField {
236    pub fn into_vec(self) -> Vec<CircleSpec> {
237        match self {
238            CircleField::One(c) => vec![c],
239            CircleField::Many(v) => v,
240        }
241    }
242
243    pub fn iter(&self) -> impl Iterator<Item = &CircleSpec> {
244        match self {
245            CircleField::One(c) => std::slice::from_ref(c).iter(),
246            CircleField::Many(v) => v.iter(),
247        }
248    }
249}
250
251/// How to generate atom index / map-number labels.
252#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
253#[serde(rename_all = "snake_case")]
254#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
255#[cfg_attr(feature = "codegen", ts(export))]
256pub enum AtomNumberBy {
257    #[default]
258    Index,
259    Mapno,
260}
261
262/// Atom numbering policy (singular wire field `atom_number`).
263#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
264#[serde(untagged)]
265#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
266#[cfg_attr(feature = "codegen", ts(export))]
267pub enum AtomNumberSpec {
268    /// Shorthand: `"index"` or `"mapno"`.
269    ByName(AtomNumberBy),
270    /// Full policy object.
271    Policy(AtomNumberPolicy),
272}
273
274/// Expanded atom-number policy.
275#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
276#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
277#[cfg_attr(feature = "codegen", ts(export))]
278pub struct AtomNumberPolicy {
279    #[serde(default)]
280    pub by: AtomNumberBy,
281    /// Restrict to these atom indices (omit = all).
282    #[serde(default, skip_serializing_if = "Option::is_none")]
283    #[cfg_attr(feature = "codegen", ts(optional))]
284    pub only: Option<Vec<u32>>,
285    #[serde(default, skip_serializing_if = "Option::is_none")]
286    #[cfg_attr(feature = "codegen", ts(optional))]
287    pub scale: Option<f64>,
288    #[serde(default, skip_serializing_if = "Option::is_none")]
289    #[cfg_attr(feature = "codegen", ts(optional))]
290    pub color: Option<String>,
291    #[serde(default, skip_serializing_if = "Option::is_none")]
292    #[cfg_attr(feature = "codegen", ts(optional))]
293    pub z: Option<i32>,
294}
295
296impl AtomNumberSpec {
297    pub fn policy(&self) -> AtomNumberPolicy {
298        match self {
299            AtomNumberSpec::ByName(by) => AtomNumberPolicy {
300                by: *by,
301                only: None,
302                scale: None,
303                color: None,
304                z: None,
305            },
306            AtomNumberSpec::Policy(p) => p.clone(),
307        }
308    }
309}
310
311/// Per-atom arbitrary text. Bare map `{ "0": "α" }` or `{ "labels": {…}, "scale"? }`.
312#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
313#[serde(untagged)]
314#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
315#[cfg_attr(feature = "codegen", ts(export))]
316pub enum AtomLabelSpec {
317    /// Keys are atom index strings (`"0"`, `"3"`).
318    Map(BTreeMap<String, MolText>),
319    /// Map plus shared style.
320    Detailed(AtomLabelDetailed),
321}
322
323/// Expanded atom-label bag with optional shared scale/color/z.
324#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
325#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
326#[cfg_attr(feature = "codegen", ts(export))]
327pub struct AtomLabelDetailed {
328    #[serde(default)]
329    pub labels: BTreeMap<String, MolText>,
330    #[serde(default, skip_serializing_if = "Option::is_none")]
331    #[cfg_attr(feature = "codegen", ts(optional))]
332    pub scale: Option<f64>,
333    #[serde(default, skip_serializing_if = "Option::is_none")]
334    #[cfg_attr(feature = "codegen", ts(optional))]
335    pub color: Option<String>,
336    #[serde(default, skip_serializing_if = "Option::is_none")]
337    #[cfg_attr(feature = "codegen", ts(optional))]
338    pub z: Option<i32>,
339}
340
341impl AtomLabelSpec {
342    pub fn entries(
343        &self,
344    ) -> (
345        &BTreeMap<String, MolText>,
346        Option<f64>,
347        Option<String>,
348        Option<i32>,
349    ) {
350        match self {
351            AtomLabelSpec::Map(m) => (m, None, None, None),
352            AtomLabelSpec::Detailed(d) => (&d.labels, d.scale, d.color.clone(), d.z),
353        }
354    }
355}
356
357/// Callout annotation (arrow / freer placement).
358#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
359#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
360#[cfg_attr(feature = "codegen", ts(export))]
361pub struct CalloutSpec {
362    #[serde(default, skip_serializing_if = "Option::is_none")]
363    #[cfg_attr(feature = "codegen", ts(optional))]
364    pub atoms: Option<Vec<u32>>,
365    #[serde(default, skip_serializing_if = "Option::is_none")]
366    #[cfg_attr(feature = "codegen", ts(optional))]
367    pub bonds: Option<Vec<(u32, u32)>>,
368    pub text: MolText,
369    #[serde(default = "default_true")]
370    pub arrow: bool,
371    #[serde(default, skip_serializing_if = "Option::is_none")]
372    #[cfg_attr(feature = "codegen", ts(optional))]
373    pub prefer: Option<LabelPos>,
374    #[serde(default, skip_serializing_if = "Option::is_none")]
375    #[cfg_attr(feature = "codegen", ts(optional))]
376    pub color: Option<String>,
377    #[serde(default, skip_serializing_if = "Option::is_none")]
378    #[cfg_attr(feature = "codegen", ts(optional))]
379    pub scale: Option<f64>,
380    #[serde(default, skip_serializing_if = "Option::is_none")]
381    #[cfg_attr(feature = "codegen", ts(optional))]
382    pub z: Option<i32>,
383}
384
385fn default_true() -> bool {
386    true
387}
388
389#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
390#[serde(untagged)]
391#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
392#[cfg_attr(feature = "codegen", ts(export))]
393pub enum CalloutField {
394    One(CalloutSpec),
395    Many(Vec<CalloutSpec>),
396}
397
398impl CalloutField {
399    pub fn into_vec(self) -> Vec<CalloutSpec> {
400        match self {
401            CalloutField::One(c) => vec![c],
402            CalloutField::Many(v) => v,
403        }
404    }
405
406    pub fn iter(&self) -> impl Iterator<Item = &CalloutSpec> {
407        match self {
408            CalloutField::One(c) => std::slice::from_ref(c).iter(),
409            CalloutField::Many(v) => v.iter(),
410        }
411    }
412}
413
414// ---------------------------------------------------------------------------
415// Default z bands (back → front)
416//
417// **Atoms/bonds sit at 0.** Behind = negative, in front = positive.
418// Gaps between bands leave room for user `z` overrides without colliding.
419// ---------------------------------------------------------------------------
420
421/// Scene / page background (behind regions).
422pub const Z_BACKGROUND: i32 = -60;
423/// Region fill/stroke (base underlay under shade).
424pub const Z_REGION: i32 = -40;
425/// Colormap wash.
426pub const Z_SHADE: i32 = -20;
427/// Bond / label halos.
428pub const Z_HALO: i32 = -10;
429/// Backbone bonds and atom element ink (origin for relative placement).
430pub const Z_BONDS: i32 = 0;
431/// Alias of [`Z_BONDS`] — atom centers share the skeleton band.
432pub const Z_ATOMS: i32 = 0;
433/// Highlight / aromatic circles (just in front of skeleton).
434pub const Z_CIRCLE: i32 = 10;
435/// Chem glyphs, `atom_number`, `atom_label`.
436pub const Z_ATOM_LABEL: i32 = 20;
437/// Region / circle text — front label layer (never under shade).
438pub const Z_REGION_LABEL: i32 = Z_ATOM_LABEL;
439/// Callouts and other free annotations.
440pub const Z_CALLOUT: i32 = 40;
441/// Mol `name` / figure labels on top.
442pub const Z_NAME: i32 = 60;
443
444// ---------------------------------------------------------------------------
445// Internal Annotation IR (B) — not codegen-exported
446// ---------------------------------------------------------------------------
447
448/// Label role on the atom tracks.
449#[derive(Debug, Clone, Copy, PartialEq, Eq)]
450pub enum LabelRole {
451    Number,
452    Text,
453}
454
455/// Internal overlay unit for paint / occupancy.
456#[derive(Debug, Clone, PartialEq)]
457pub enum Annotation {
458    Shade {
459        spec: ShadeSpec,
460        z: i32,
461    },
462    Region {
463        spec: RegionSpec,
464        z: i32,
465    },
466    Circle {
467        spec: CircleSpec,
468        z: i32,
469        /// True when synthesized from aromatic circle paint opt.
470        from_aromatic: bool,
471    },
472    /// Per-atom number or text label.
473    AtomLabel {
474        atom: u32,
475        text: MolText,
476        role: LabelRole,
477        scale: Option<f64>,
478        color: Option<String>,
479        z: i32,
480    },
481    Callout {
482        spec: CalloutSpec,
483        z: i32,
484    },
485}
486
487impl Annotation {
488    pub fn z(&self) -> i32 {
489        match self {
490            Annotation::Shade { z, .. }
491            | Annotation::Region { z, .. }
492            | Annotation::Circle { z, .. }
493            | Annotation::AtomLabel { z, .. }
494            | Annotation::Callout { z, .. } => *z,
495        }
496    }
497}
498
499/// Overlay fields extracted from / applied to a mol (excludes privileged `name`).
500#[derive(Debug, Clone, Default, PartialEq)]
501pub struct MolOverlayFields {
502    pub shade: Option<ShadeSpec>,
503    pub atom_number: Option<AtomNumberSpec>,
504    pub atom_label: Option<AtomLabelSpec>,
505    pub region: Option<RegionField>,
506    pub circle: Option<CircleField>,
507    pub callout: Option<CalloutField>,
508}
509
510/// Read overlay chrome from a mol node (wire A → bag).
511pub fn overlay_from_mol(
512    shade: &Option<ShadeSpec>,
513    atom_number: &Option<AtomNumberSpec>,
514    atom_label: &Option<AtomLabelSpec>,
515    region: &Option<RegionField>,
516    circle: &Option<CircleField>,
517    callout: &Option<CalloutField>,
518) -> MolOverlayFields {
519    MolOverlayFields {
520        shade: shade.clone(),
521        atom_number: atom_number.clone(),
522        atom_label: atom_label.clone(),
523        region: region.clone(),
524        circle: circle.clone(),
525        callout: callout.clone(),
526    }
527}
528
529/// A→B: expand wire overlay fields into a sorted annotation list.
530///
531/// Privileged mol `name` is **not** included (caption path stays separate).
532/// `atom_number` expands to one [`Annotation::AtomLabel`] per selected atom
533/// with placeholder text; callers that know mapnos resolve text at paint time.
534pub fn annotations_from_overlay(overlay: &MolOverlayFields) -> Vec<Annotation> {
535    let mut out = Vec::new();
536
537    if let Some(ref shade) = overlay.shade {
538        out.push(Annotation::Shade {
539            spec: shade.clone(),
540            z: Z_SHADE,
541        });
542    }
543
544    if let Some(ref regions) = overlay.region {
545        for r in regions.iter() {
546            let z = r.z.unwrap_or(Z_REGION);
547            out.push(Annotation::Region { spec: r.clone(), z });
548        }
549    }
550
551    if let Some(ref circles) = overlay.circle {
552        for c in circles.iter() {
553            let z = c.z.unwrap_or(Z_CIRCLE);
554            out.push(Annotation::Circle {
555                spec: c.clone(),
556                z,
557                from_aromatic: false,
558            });
559        }
560    }
561
562    if let Some(ref num) = overlay.atom_number {
563        let policy = num.policy();
564        let z = policy.z.unwrap_or(Z_ATOM_LABEL);
565        let atoms: Vec<u32> = policy.only.clone().unwrap_or_else(|| {
566            // Without a molecule, emit a sentinel empty — paint fills from layout.
567            Vec::new()
568        });
569        if atoms.is_empty() {
570            // Keep policy as a single marker annotation using atom 0 placeholder
571            // only when `only` is set; otherwise store via AtomLabel with atom=u32::MAX
572            // is messy. Instead push one Annotation per explicit `only`, or a
573            // NumberPolicy carrier — use AtomLabel with text encoding by:.
574            out.push(Annotation::AtomLabel {
575                atom: u32::MAX,
576                text: MolText::Plain(match policy.by {
577                    AtomNumberBy::Index => "__number_index__".into(),
578                    AtomNumberBy::Mapno => "__number_mapno__".into(),
579                }),
580                role: LabelRole::Number,
581                scale: policy.scale,
582                color: policy.color.clone(),
583                z,
584            });
585        } else {
586            for a in atoms {
587                let text = match policy.by {
588                    AtomNumberBy::Index => MolText::Plain(a.to_string()),
589                    AtomNumberBy::Mapno => MolText::Plain(format!("m{a}")),
590                };
591                out.push(Annotation::AtomLabel {
592                    atom: a,
593                    text,
594                    role: LabelRole::Number,
595                    scale: policy.scale,
596                    color: policy.color.clone(),
597                    z,
598                });
599            }
600        }
601    }
602
603    if let Some(ref labels) = overlay.atom_label {
604        let (map, scale, color, z_opt) = labels.entries();
605        let z = z_opt.unwrap_or(Z_ATOM_LABEL);
606        for (k, text) in map {
607            let Ok(atom) = k.parse::<u32>() else {
608                continue;
609            };
610            out.push(Annotation::AtomLabel {
611                atom,
612                text: text.clone(),
613                role: LabelRole::Text,
614                scale,
615                color: color.clone(),
616                z,
617            });
618        }
619    }
620
621    if let Some(ref callouts) = overlay.callout {
622        for c in callouts.iter() {
623            let z = c.z.unwrap_or(Z_CALLOUT);
624            out.push(Annotation::Callout { spec: c.clone(), z });
625        }
626    }
627
628    out.sort_by_key(|a| a.z());
629    out
630}
631
632/// B→A: rebuild wire overlay fields from annotations (canonical form).
633pub fn overlay_from_annotations(anns: &[Annotation]) -> MolOverlayFields {
634    let mut shade: Option<ShadeSpec> = None;
635    let mut regions: Vec<RegionSpec> = Vec::new();
636    let mut circles: Vec<CircleSpec> = Vec::new();
637    let mut number_policy: Option<AtomNumberPolicy> = None;
638    let mut number_atoms: Vec<(u32, MolText)> = Vec::new();
639    let mut text_labels: BTreeMap<String, MolText> = BTreeMap::new();
640    let mut text_scale: Option<f64> = None;
641    let mut text_color: Option<String> = None;
642    let mut text_z: Option<i32> = None;
643    let mut callouts: Vec<CalloutSpec> = Vec::new();
644
645    for a in anns {
646        match a {
647            Annotation::Shade { spec, .. } => {
648                shade = Some(spec.clone());
649            }
650            Annotation::Region { spec, .. } => {
651                regions.push(spec.clone());
652            }
653            Annotation::Circle {
654                spec,
655                from_aromatic,
656                ..
657            } => {
658                if !from_aromatic {
659                    circles.push(spec.clone());
660                }
661            }
662            Annotation::AtomLabel {
663                atom,
664                text,
665                role,
666                scale,
667                color,
668                z,
669            } => match role {
670                LabelRole::Number => {
671                    if *atom == u32::MAX {
672                        let by = match text.content() {
673                            "__number_mapno__" => AtomNumberBy::Mapno,
674                            _ => AtomNumberBy::Index,
675                        };
676                        number_policy = Some(AtomNumberPolicy {
677                            by,
678                            only: None,
679                            scale: *scale,
680                            color: color.clone(),
681                            z: Some(*z),
682                        });
683                    } else {
684                        number_atoms.push((*atom, text.clone()));
685                        number_policy.get_or_insert(AtomNumberPolicy {
686                            by: AtomNumberBy::Index,
687                            only: None,
688                            scale: *scale,
689                            color: color.clone(),
690                            z: Some(*z),
691                        });
692                    }
693                }
694                LabelRole::Text => {
695                    text_labels.insert(atom.to_string(), text.clone());
696                    if text_scale.is_none() {
697                        text_scale = *scale;
698                    }
699                    if text_color.is_none() {
700                        text_color = color.clone();
701                    }
702                    if text_z.is_none() {
703                        text_z = Some(*z);
704                    }
705                }
706            },
707            Annotation::Callout { spec, .. } => {
708                callouts.push(spec.clone());
709            }
710        }
711    }
712
713    let atom_number = if let Some(mut p) = number_policy {
714        if !number_atoms.is_empty() {
715            let mut only: Vec<u32> = number_atoms.iter().map(|(a, _)| *a).collect();
716            only.sort_unstable();
717            only.dedup();
718            p.only = Some(only);
719        }
720        // Canonical shorthand when possible.
721        let spec = if p.only.is_none() && p.scale.is_none() && p.color.is_none() && p.z.is_none() {
722            AtomNumberSpec::ByName(p.by)
723        } else if p.scale.is_none()
724            && p.color.is_none()
725            && (p.z.is_none() || p.z == Some(Z_ATOM_LABEL))
726            && p.only.is_none()
727        {
728            AtomNumberSpec::ByName(p.by)
729        } else {
730            // Drop default z for cleaner wire.
731            if p.z == Some(Z_ATOM_LABEL) {
732                p.z = None;
733            }
734            AtomNumberSpec::Policy(p)
735        };
736        Some(spec)
737    } else {
738        None
739    };
740
741    let atom_label = if text_labels.is_empty() {
742        None
743    } else if text_scale.is_none()
744        && text_color.is_none()
745        && text_z.filter(|&z| z != Z_ATOM_LABEL).is_none()
746    {
747        Some(AtomLabelSpec::Map(text_labels))
748    } else {
749        Some(AtomLabelSpec::Detailed(AtomLabelDetailed {
750            labels: text_labels,
751            scale: text_scale,
752            color: text_color,
753            z: text_z.filter(|&z| z != Z_ATOM_LABEL),
754        }))
755    };
756
757    let region = match regions.len() {
758        0 => None,
759        1 => Some(RegionField::One(regions.pop().unwrap())),
760        _ => Some(RegionField::Many(regions)),
761    };
762    let circle = match circles.len() {
763        0 => None,
764        1 => Some(CircleField::One(circles.pop().unwrap())),
765        _ => Some(CircleField::Many(circles)),
766    };
767    let callout = match callouts.len() {
768        0 => None,
769        1 => Some(CalloutField::One(callouts.pop().unwrap())),
770        _ => Some(CalloutField::Many(callouts)),
771    };
772
773    MolOverlayFields {
774        shade,
775        atom_number,
776        atom_label,
777        region,
778        circle,
779        callout,
780    }
781}
782
783/// Canonicalize overlay by A→B→A (stable for round-trip tests).
784pub fn canonicalize_overlay(overlay: &MolOverlayFields) -> MolOverlayFields {
785    overlay_from_annotations(&annotations_from_overlay(overlay))
786}
787
788#[cfg(test)]
789mod tests {
790    use super::*;
791
792    #[test]
793    fn mol_text_plain_and_styled() {
794        let plain = MolText::Plain("ethanol".into());
795        assert_eq!(plain.content(), "ethanol");
796        let styled = MolText::Styled(MolTextSpec {
797            content: "pocket".into(),
798            place: Some(RegionTextPlace::Inside),
799            ..Default::default()
800        });
801        assert_eq!(styled.as_styled().place, Some(RegionTextPlace::Inside));
802    }
803
804    #[test]
805    fn round_trip_shade_and_region() {
806        let overlay = MolOverlayFields {
807            shade: Some(ShadeSpec {
808                atoms: Some(vec![0.1, 0.5]),
809                ..Default::default()
810            }),
811            region: Some(RegionField::One(RegionSpec {
812                style: RegionStyle::Box,
813                atoms: vec![0, 1, 2],
814                exclude: vec![3],
815                fill: Some(FillSpec {
816                    color: Some("#c44".into()),
817                    opacity: Some(0.15),
818                }),
819                stroke: None,
820                text: Some(MolText::Plain("pocket".into())),
821                z: None,
822            })),
823            ..Default::default()
824        };
825        let back = canonicalize_overlay(&overlay);
826        assert_eq!(
827            back.shade.as_ref().unwrap().atoms,
828            overlay.shade.as_ref().unwrap().atoms
829        );
830        let r = match back.region.unwrap() {
831            RegionField::One(r) => r,
832            RegionField::Many(_) => panic!("expected one region"),
833        };
834        assert_eq!(r.atoms, vec![0, 1, 2]);
835        assert_eq!(r.exclude, vec![3]);
836    }
837
838    #[test]
839    fn round_trip_atom_label_map() {
840        let mut labels = BTreeMap::new();
841        labels.insert("1".into(), MolText::Plain("α".into()));
842        labels.insert("2".into(), MolText::Plain("N-Me".into()));
843        let overlay = MolOverlayFields {
844            atom_label: Some(AtomLabelSpec::Detailed(AtomLabelDetailed {
845                labels,
846                scale: Some(0.9),
847                color: None,
848                z: None,
849            })),
850            ..Default::default()
851        };
852        let back = canonicalize_overlay(&overlay);
853        let atom_label = back.atom_label.unwrap();
854        let (map, scale, _, _) = atom_label.entries();
855        assert_eq!(map.get("1").unwrap().content(), "α");
856        assert_eq!(map.get("2").unwrap().content(), "N-Me");
857        assert_eq!(scale, Some(0.9));
858    }
859
860    #[test]
861    fn round_trip_atom_number_shorthand() {
862        let overlay = MolOverlayFields {
863            atom_number: Some(AtomNumberSpec::ByName(AtomNumberBy::Index)),
864            ..Default::default()
865        };
866        let anns = annotations_from_overlay(&overlay);
867        assert!(matches!(
868            &anns[0],
869            Annotation::AtomLabel {
870                role: LabelRole::Number,
871                atom: u32::MAX,
872                ..
873            }
874        ));
875        let back = overlay_from_annotations(&anns);
876        assert!(matches!(
877            back.atom_number,
878            Some(AtomNumberSpec::ByName(AtomNumberBy::Index))
879        ));
880    }
881
882    #[test]
883    fn round_trip_circle_and_callout() {
884        let overlay = MolOverlayFields {
885            circle: Some(CircleField::One(CircleSpec {
886                atoms: vec![1, 2],
887                bonds: vec![(0, 1)],
888                ring: None,
889                fill: None,
890                stroke: Some(StrokeSpec {
891                    color: Some("#06c".into()),
892                    width: Some(1.5),
893                    dash: None,
894                }),
895                scale: None,
896                z: None,
897            })),
898            callout: Some(CalloutField::One(CalloutSpec {
899                atoms: Some(vec![2]),
900                bonds: None,
901                text: MolText::Plain("note".into()),
902                arrow: true,
903                prefer: Some(LabelPos::Left),
904                color: None,
905                scale: None,
906                z: None,
907            })),
908            ..Default::default()
909        };
910        let back = canonicalize_overlay(&overlay);
911        assert!(back.circle.is_some());
912        let circ = match back.circle.as_ref().unwrap() {
913            CircleField::One(c) => c,
914            CircleField::Many(v) => &v[0],
915        };
916        assert_eq!(circ.bonds, vec![(0, 1)]);
917        assert!(back.callout.is_some());
918    }
919
920    #[test]
921    fn annotations_sort_by_z() {
922        let overlay = MolOverlayFields {
923            shade: Some(ShadeSpec::default()),
924            region: Some(RegionField::One(RegionSpec {
925                style: RegionStyle::Box,
926                atoms: vec![0],
927                exclude: vec![],
928                fill: None,
929                stroke: None,
930                text: None,
931                z: None,
932            })),
933            callout: Some(CalloutField::One(CalloutSpec {
934                atoms: Some(vec![0]),
935                bonds: None,
936                text: MolText::Plain("x".into()),
937                arrow: false,
938                prefer: None,
939                color: None,
940                scale: None,
941                z: None,
942            })),
943            ..Default::default()
944        };
945        let zs: Vec<_> = annotations_from_overlay(&overlay)
946            .iter()
947            .map(Annotation::z)
948            .collect();
949        assert!(zs.windows(2).all(|w| w[0] <= w[1]));
950        assert_eq!(zs.first(), Some(&Z_REGION));
951        assert_eq!(zs.last(), Some(&Z_CALLOUT));
952        assert!(Z_BACKGROUND < Z_REGION);
953        assert!(Z_REGION < Z_SHADE);
954        assert!(Z_REGION_LABEL > Z_SHADE);
955        assert_eq!(Z_REGION_LABEL, Z_ATOM_LABEL);
956        assert!(Z_SHADE < Z_HALO);
957        assert!(Z_HALO < Z_BONDS);
958        assert_eq!(Z_BONDS, Z_ATOMS);
959        assert_eq!(Z_BONDS, 0);
960        assert!(Z_CIRCLE > Z_BONDS);
961        assert!(Z_ATOM_LABEL > Z_CIRCLE);
962        assert!(Z_CALLOUT > Z_ATOM_LABEL);
963        assert!(Z_NAME > Z_CALLOUT);
964    }
965
966    #[test]
967    fn json_wire_shapes_round_trip_serde() {
968        let name: MolText = serde_json::from_str(r#""ethanol""#).unwrap();
969        assert_eq!(name.content(), "ethanol");
970        let region: RegionField = serde_json::from_str(
971            r#"{"style":"bezier","atoms":[0,1],"exclude":[2],"text":{"content":"A","place":"inside"}}"#,
972        )
973        .unwrap();
974        match region {
975            RegionField::One(r) => {
976                assert_eq!(r.style, RegionStyle::Bezier);
977                assert_eq!(
978                    r.text.unwrap().as_styled().place,
979                    Some(RegionTextPlace::Inside)
980                );
981            }
982            _ => panic!(),
983        }
984        let num: AtomNumberSpec = serde_json::from_str(r#""mapno""#).unwrap();
985        assert!(matches!(num, AtomNumberSpec::ByName(AtomNumberBy::Mapno)));
986    }
987}