Skip to main content

xpict_core/doc/
depict_doc.rs

1//! Single document entry: plan → resolve edge in-core → render.
2//!
3//! Same shape as the JS wrapper (`planEdge` → `processEdgePlan` → `renderDoc`),
4//! without leaving Rust or marshalling to JSON between steps.
5
6use serde::{Deserialize, Serialize};
7
8use super::edge_resolve::process_edge_plan_with_frames;
9use super::{
10    assign_mol_ids, compose_scheme, plan_edge, render_doc, DepictSpec, DocPaint, MolNode, Node,
11};
12use crate::scene::{MoleculeIn, Scene};
13
14/// One painted molecule ready for hosts (parity with JS / Python ``Rendered``).
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct Rendered {
17    pub id: String,
18    pub width: f64,
19    pub height: f64,
20    pub scene: Scene,
21    pub molecule: MoleculeIn,
22    pub source: String,
23    pub frame_molblock: String,
24    pub coords: Vec<SvgAtom>,
25    pub svg_coords: Vec<SvgAtom>,
26    pub bonds: Vec<SvgBond>,
27}
28
29/// Atom position in SCALE / SVG space (host ``Rendered.coords``).
30#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
31pub struct SvgAtom {
32    pub index: i32,
33    pub element: String,
34    pub x: f64,
35    pub y: f64,
36    #[serde(default, skip_serializing_if = "Option::is_none")]
37    pub label: Option<String>,
38    pub charge: i32,
39}
40
41/// Bond endpoints in layout order.
42#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
43pub struct SvgBond {
44    pub index: i32,
45    pub begin: i32,
46    pub end: i32,
47    pub order: f64,
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub stereo: Option<String>,
50}
51
52fn source_of(node: &MolNode) -> Result<String, String> {
53    node.structure().map(str::to_string)
54}
55
56fn pack_rendered(row: DocPaint, source: String) -> Rendered {
57    let coords: Vec<SvgAtom> = row
58        .molecule
59        .atoms
60        .iter()
61        .map(|a| SvgAtom {
62            index: a.index,
63            element: a.symbol().to_string(),
64            x: a.x,
65            y: a.y,
66            label: a.label.clone(),
67            charge: a.charge,
68        })
69        .collect();
70    let bonds: Vec<SvgBond> = row
71        .molecule
72        .bonds
73        .iter()
74        .map(|b| SvgBond {
75            index: b.index,
76            begin: b.begin,
77            end: b.end,
78            order: b.order,
79            stereo: b.stereo.clone(),
80        })
81        .collect();
82    Rendered {
83        id: row.id,
84        width: row.scene.width,
85        height: row.scene.height,
86        scene: row.scene,
87        molecule: row.molecule,
88        source,
89        frame_molblock: row.frame_json,
90        svg_coords: coords.clone(),
91        coords,
92        bonds,
93    }
94}
95
96/// Layout every mol (CoordGen), paint the mol spec, return one row per mol.
97fn paint_document(spec: &DepictSpec) -> Result<Vec<Rendered>, String> {
98    let Some(plan) = plan_edge(spec)? else {
99        return Ok(vec![]);
100    };
101    let (edge, frames) = process_edge_plan_with_frames(&plan)?;
102    let mut painted = render_doc(spec, &edge)?;
103    for row in &mut painted {
104        if let Some(frame) = frames.get(&row.id) {
105            row.frame_json = frame.clone();
106        }
107    }
108
109    let mols = spec.mols();
110    let ids = assign_mol_ids(&mols)?;
111    let mut out = Vec::with_capacity(painted.len());
112    for row in painted {
113        let source = mols
114            .iter()
115            .zip(ids.iter())
116            .find(|(_, id)| *id == &row.id)
117            .map(|(n, _)| source_of(n))
118            .transpose()?
119            .unwrap_or_else(|| row.id.clone());
120        out.push(pack_rendered(row, source));
121    }
122    Ok(out)
123}
124
125fn rendered_to_paint(row: &Rendered) -> DocPaint {
126    DocPaint {
127        id: row.id.clone(),
128        molecule: row.molecule.clone(),
129        scene: row.scene.clone(),
130        frame_json: row.frame_molblock.clone(),
131    }
132}
133
134fn compose_cell(spec: &DepictSpec, rows: &[Rendered]) -> Result<Rendered, String> {
135    let paints: Vec<DocPaint> = rows.iter().map(rendered_to_paint).collect();
136    let scene = compose_scheme(spec, &paints)?;
137    let mut cell = rows[0].clone();
138    cell.source = "reaction_scheme".into();
139    cell.width = scene.width;
140    cell.height = scene.height;
141    cell.scene = scene;
142    Ok(cell)
143}
144
145fn take_cells(
146    spec: &DepictSpec,
147    painted: &[Rendered],
148    i: &mut usize,
149) -> Result<Vec<Rendered>, String> {
150    match spec {
151        DepictSpec::Mol(_) => {
152            let row = painted
153                .get(*i)
154                .ok_or_else(|| "render paint underflow".to_string())?
155                .clone();
156            *i += 1;
157            Ok(vec![row])
158        }
159        DepictSpec::Group { children, .. } => {
160            let mut out = Vec::new();
161            for n in children {
162                if matches!(n, Node::Mol(_)) {
163                    let row = painted
164                        .get(*i)
165                        .ok_or_else(|| "render paint underflow".to_string())?
166                        .clone();
167                    *i += 1;
168                    out.push(row);
169                }
170            }
171            Ok(out)
172        }
173        DepictSpec::ReactionScheme { .. } => {
174            let n = spec.mols().len();
175            if *i + n > painted.len() {
176                return Err("render paint underflow".into());
177            }
178            let slice = &painted[*i..*i + n];
179            *i += n;
180            if slice.is_empty() {
181                return Ok(vec![]);
182            }
183            Ok(vec![compose_cell(spec, slice)?])
184        }
185        DepictSpec::Grid { children, .. } => {
186            let mut out = Vec::new();
187            for row in children {
188                out.extend(take_cells(row, painted, i)?);
189            }
190            Ok(out)
191        }
192    }
193}
194
195/// Product entry: layout + mol-spec paint + pack cells (schemes compose).
196///
197/// Every mol goes through the same paint steps. Annotations on [`MolNode`]
198/// (`region`, `callout`, `circle`, `atom_label`, `atom_number`, `name`,
199/// `shade`) are part of that path, not a special case.
200pub fn render(spec: &DepictSpec) -> Result<Vec<Rendered>, String> {
201    let painted = paint_document(spec)?;
202    let mut i = 0;
203    let cells = take_cells(spec, &painted, &mut i)?;
204    if i != painted.len() {
205        return Err(format!(
206            "render pack leftover paints: used {i} of {}",
207            painted.len()
208        ));
209    }
210    Ok(cells)
211}
212
213/// Alias of [`render`].
214pub fn depict(spec: &DepictSpec) -> Result<Vec<Rendered>, String> {
215    render(spec)
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221    use crate::doc::chrome::{
222        AtomLabelSpec, AtomNumberBy, AtomNumberSpec, CalloutField, CalloutSpec, CircleField,
223        CircleSpec, FillSpec, MolText, RegionField, RegionSpec, RegionStyle, StrokeSpec,
224    };
225    use crate::doc::{
226        AlignTo, EdgeArrow, EdgeNode, EdgeNodeKind, MolIds, MolNode, Node, ShadeSpec,
227    };
228    use crate::scene::{LayerName, Primitive};
229    use std::collections::BTreeMap;
230
231    fn scene_classes(scene: &Scene) -> Vec<String> {
232        let mut out = Vec::new();
233        for vp in &scene.viewports {
234            for layer in &vp.layers {
235                for p in &layer.primitives {
236                    if let Some(c) = prim_class(p) {
237                        out.push(c.to_string());
238                    }
239                }
240            }
241        }
242        for p in scene.overlays.iter().chain(scene.halo.iter()) {
243            if let Some(c) = prim_class(p) {
244                out.push(c.to_string());
245            }
246        }
247        out
248    }
249
250    fn prim_class(p: &Primitive) -> Option<&str> {
251        match p {
252            Primitive::Path { class, .. }
253            | Primitive::Circle { class, .. }
254            | Primitive::Text { class, .. } => class.as_deref(),
255        }
256    }
257
258    #[test]
259    fn depict_ethanol() {
260        let spec = DepictSpec::Mol(MolNode {
261            smiles: Some("CCO".into()),
262            cxsmiles: None,
263            molfile: None,
264            id: None,
265            shade: None,
266            star_labels: None,
267            align_to: None,
268            label: None,
269            name: None,
270            atom_number: None,
271            atom_label: None,
272            region: None,
273            circle: None,
274            callout: None,
275            color: None,
276            scale: None,
277            weight: None,
278            halo: None,
279            aromatic: None,
280            debug_box: None,
281            debug_align: None,
282            pad: None,
283            opts: None,
284            ..Default::default()
285        });
286        let painted = depict(&spec).unwrap();
287        assert_eq!(painted.len(), 1);
288        assert_eq!(painted[0].molecule.atoms.len(), 3);
289        assert_eq!(painted[0].source, "CCO");
290        assert_eq!(painted[0].coords.len(), 3);
291        assert!(!painted[0].frame_molblock.is_empty());
292    }
293
294    #[test]
295    fn depict_ethanol_and_aniline_paint_implicit_h_labels() {
296        for (smiles, needle) in [("CCO", "OH"), ("c1ccccc1N", "NH₂")] {
297            let spec = DepictSpec::Mol(MolNode {
298                smiles: Some(smiles.into()),
299                cxsmiles: None,
300                molfile: None,
301                id: None,
302                shade: None,
303                star_labels: None,
304                align_to: None,
305                label: None,
306                name: None,
307                atom_number: None,
308                atom_label: None,
309                region: None,
310                circle: None,
311                callout: None,
312                color: None,
313                scale: None,
314                weight: None,
315                halo: None,
316                aromatic: None,
317                debug_box: None,
318                debug_align: None,
319                pad: None,
320                opts: None,
321                ..Default::default()
322            });
323            let painted = depict(&spec).unwrap();
324            let scene = &painted[0].scene;
325            let texts: Vec<&str> = scene
326                .viewports
327                .iter()
328                .flat_map(|v| v.layers.iter())
329                .flat_map(|l| l.primitives.iter())
330                .filter_map(|p| match p {
331                    crate::scene::Primitive::Path {
332                        data_text: Some(t), ..
333                    } => Some(t.as_str()),
334                    _ => None,
335                })
336                .collect();
337            let ok = texts.iter().any(|t| {
338                t.contains(needle)
339                    || (needle == "OH" && (*t == "HO" || *t == "OH"))
340                    || (needle == "NH₂" && (t.contains("H₂N") || t.contains("NH₂")))
341            });
342            assert!(
343                ok,
344                "{smiles}: expected {needle:?} (or flipped) in label texts {texts:?}"
345            );
346            assert!(
347                !texts.iter().any(|t| *t == "O" || *t == "N"),
348                "{smiles}: bare O/N without H, got {texts:?}"
349            );
350        }
351    }
352
353    #[test]
354    fn depict_aligned_pair() {
355        let spec = DepictSpec::Group {
356            id: None,
357            align: true,
358            children: vec![
359                Node::Mol(MolNode {
360                    id: Some("a".into()),
361                    smiles: Some("c1ccccc1".into()),
362                    ..Default::default()
363                }),
364                Node::Mol(MolNode {
365                    id: Some("b".into()),
366                    smiles: Some("Cc1ccccc1".into()),
367                    align_to: Some(AlignTo::Ref("a".into())),
368                    ..Default::default()
369                }),
370            ],
371            opts: None,
372            color: None,
373            scale: None,
374            aromatic: None,
375            debug_box: None,
376            debug_align: None,
377            pad: None,
378        };
379        let painted = depict(&spec).unwrap();
380        assert_eq!(painted.len(), 2);
381        assert!(painted[1].molecule.align_debug.is_some());
382        assert_eq!(painted[0].source, "c1ccccc1");
383    }
384
385    /// Same overlay bag a lone mol and a scheme child both accept (one MolNode).
386    fn kitchen_sink_mol() -> MolNode {
387        MolNode {
388            id: Some("ph".into()),
389            smiles: Some("c1ccccc1O".into()),
390            name: Some(MolText::Plain("phenol".into())),
391            shade: Some(ShadeSpec {
392                atoms: Some(vec![0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.0]),
393                ..Default::default()
394            }),
395            atom_number: Some(AtomNumberSpec::ByName(AtomNumberBy::Index)),
396            atom_label: Some(AtomLabelSpec::Map(BTreeMap::from([(
397                "6".into(),
398                MolText::Plain("exo".into()),
399            )]))),
400            circle: Some(CircleField::One(CircleSpec {
401                atoms: vec![6],
402                bonds: vec![],
403                ring: None,
404                fill: None,
405                stroke: None,
406                scale: None,
407                z: None,
408            })),
409            region: Some(RegionField::One(RegionSpec {
410                style: RegionStyle::Box,
411                atoms: vec![0, 1, 2, 3, 4, 5],
412                exclude: vec![],
413                fill: None,
414                stroke: None,
415                text: Some(MolText::Plain("ring".into())),
416                z: None,
417            })),
418            callout: Some(CalloutField::One(CalloutSpec {
419                atoms: Some(vec![6]),
420                bonds: None,
421                text: MolText::Plain("OH".into()),
422                arrow: true,
423                prefer: Some(crate::doc::LabelPos::Above),
424                color: None,
425                scale: None,
426                z: None,
427            })),
428            ..Default::default()
429        }
430    }
431
432    fn assert_annotation_classes(classes: &str) {
433        for needle in [
434            "region",
435            "callout",
436            "atom-circle",
437            "atom-number",
438            "atom-label",
439            "mol-caption",
440            "shade",
441        ] {
442            assert!(
443                classes.contains(needle),
444                "missing {needle} in classes: {classes}"
445            );
446        }
447    }
448
449    #[test]
450    fn root_mol_and_scheme_child_share_molnode_json() {
451        let node = kitchen_sink_mol();
452        let root = serde_json::to_value(&DepictSpec::Mol(node.clone())).unwrap();
453        let child = serde_json::to_value(&Node::Mol(node)).unwrap();
454        assert_eq!(root, child);
455        for key in [
456            "region",
457            "circle",
458            "callout",
459            "atom_label",
460            "atom_number",
461            "name",
462            "shade",
463        ] {
464            assert!(
465                root.get(key).is_some(),
466                "missing {key} on shared MolNode JSON"
467            );
468        }
469    }
470
471    #[test]
472    fn render_annotates_mol_in_group() {
473        let spec = DepictSpec::Group {
474            id: None,
475            align: false,
476            children: vec![Node::Mol(kitchen_sink_mol())],
477            opts: None,
478            color: None,
479            scale: None,
480            aromatic: None,
481            debug_box: None,
482            debug_align: None,
483            pad: None,
484        };
485        let painted = render(&spec).unwrap();
486        assert_eq!(painted.len(), 1);
487        assert_annotation_classes(&scene_classes(&painted[0].scene).join(" "));
488    }
489
490    #[test]
491    fn render_annotates_mol_in_scheme() {
492        let spec = DepictSpec::ReactionScheme {
493            id: None,
494            children: vec![
495                Node::Mol(kitchen_sink_mol()),
496                Node::Mol(MolNode {
497                    id: Some("et".into()),
498                    smiles: Some("CCO".into()),
499                    ..Default::default()
500                }),
501                Node::Edge(crate::doc::EdgeNode {
502                    type_: crate::doc::EdgeNodeKind::Edge,
503                    sources: MolIds::One("ph".into()),
504                    targets: MolIds::One("et".into()),
505                    label: None,
506                    edge_routing: None,
507                    arrow: crate::doc::EdgeArrow::Forward,
508                    color: None,
509                    dashed: false,
510                    role: None,
511                    stroke_width: None,
512                }),
513            ],
514            layout: None,
515            opts: None,
516            color: None,
517            scale: None,
518            aromatic: None,
519            debug_box: None,
520            debug_align: None,
521            pad: None,
522        };
523        let painted = render(&spec).unwrap();
524        assert_eq!(painted.len(), 1);
525        assert_eq!(painted[0].source, "reaction_scheme");
526        assert_annotation_classes(&scene_classes(&painted[0].scene).join(" "));
527    }
528
529    #[test]
530    fn render_annotates_lone_mol_same_as_scheme() {
531        let painted = render(&DepictSpec::Mol(kitchen_sink_mol())).unwrap();
532        assert_eq!(painted.len(), 1);
533        assert_annotation_classes(&scene_classes(&painted[0].scene).join(" "));
534    }
535
536    #[test]
537    fn render_paints_circle_bond_midpoints() {
538        let spec = DepictSpec::Mol(MolNode {
539            smiles: Some("CCO".into()),
540            circle: Some(CircleField::One(CircleSpec {
541                atoms: vec![],
542                bonds: vec![(0, 1), (1, 2)],
543                ring: None,
544                fill: None,
545                stroke: Some(StrokeSpec {
546                    color: Some("#c00".into()),
547                    width: Some(1.4),
548                    dash: None,
549                }),
550                scale: None,
551                z: None,
552            })),
553            ..Default::default()
554        });
555        let painted = render(&spec).unwrap();
556        let classes = scene_classes(&painted[0].scene).join(" ");
557        assert!(classes.contains("bond-circle"), "{classes}");
558        let svg = crate::scene_to_svg(&painted[0].scene);
559        assert!(svg.contains("bond-circle"), "{svg}");
560        assert!(svg.contains("#c00"), "{svg}");
561    }
562
563    #[test]
564    fn mol_svg_is_one_group_with_nested_shading() {
565        let spec = DepictSpec::Mol(MolNode {
566            smiles: Some("*C |$GSH;$|".into()),
567            region: Some(RegionField::One(RegionSpec {
568                style: RegionStyle::Bezier,
569                atoms: vec![0],
570                exclude: vec![],
571                fill: Some(FillSpec {
572                    color: Some("#2a9d8f".into()),
573                    opacity: Some(0.25),
574                }),
575                stroke: None,
576                text: None,
577                z: None,
578            })),
579            ..Default::default()
580        });
581        let painted = render(&spec).unwrap();
582        let svg = crate::scene_to_svg(&painted[0].scene);
583        assert_eq!(
584            svg.matches(r#"class="xpict-mol""#).count(),
585            1,
586            "shading must nest inside the mol, not a sibling group: {svg}"
587        );
588        let mol = svg.find(r#"class="xpict-mol""#).unwrap();
589        let shade = svg
590            .find(r#"class="xpict-layer xpict-shading""#)
591            .expect("shading layer");
592        assert!(mol < shade, "shading group nested in mol: {svg}");
593    }
594
595    #[test]
596    fn scaled_mol_aromatic_circle_sits_in_the_ring() {
597        let spec = DepictSpec::Mol(MolNode {
598            smiles: Some("NCCc1ccccc1".into()),
599            scale: Some(0.6),
600            ..Default::default()
601        });
602        let painted = render(&spec).unwrap();
603        let vp = &painted[0].scene.viewports[0];
604        let circle = vp
605            .layers
606            .iter()
607            .filter(|l| l.name == LayerName::Marks)
608            .flat_map(|l| l.primitives.iter())
609            .find_map(|p| match p {
610                Primitive::Circle {
611                    cx,
612                    cy,
613                    r,
614                    class: Some(c),
615                    ..
616                } if c.contains("aromatic") => Some((*cx, *cy, *r)),
617                _ => None,
618            })
619            .expect("aromatic circle");
620        let mut near = 0usize;
621        for layer in &vp.layers {
622            if layer.name != LayerName::Bonds {
623                continue;
624            }
625            for p in &layer.primitives {
626                let Primitive::Path {
627                    d, class: Some(c), ..
628                } = p
629                else {
630                    continue;
631                };
632                if !c.contains("bond-skeleton") {
633                    continue;
634                }
635                for (x, y) in path_xy(d) {
636                    if (x - circle.0).hypot(y - circle.1) <= 2.5 * circle.2 {
637                        near += 1;
638                    }
639                }
640            }
641        }
642        assert!(
643            near >= 6,
644            "scale must apply to chrome and chem together; circle {:?} only near {near} skeleton ends",
645            circle
646        );
647    }
648
649    #[test]
650    fn scheme_gsh_region_covers_star_label() {
651        let spec = DepictSpec::ReactionScheme {
652            id: None,
653            children: vec![
654                Node::Mol(MolNode {
655                    id: Some("a".into()),
656                    smiles: Some("CCO".into()),
657                    ..Default::default()
658                }),
659                Node::Mol(MolNode {
660                    id: Some("b".into()),
661                    smiles: Some("*C |$GSH;$|".into()),
662                    region: Some(RegionField::One(RegionSpec {
663                        style: RegionStyle::Bezier,
664                        atoms: vec![0],
665                        exclude: vec![],
666                        fill: Some(FillSpec {
667                            color: Some("#2a9d8f".into()),
668                            opacity: Some(0.25),
669                        }),
670                        stroke: None,
671                        text: None,
672                        z: None,
673                    })),
674                    ..Default::default()
675                }),
676                Node::Edge(EdgeNode {
677                    type_: EdgeNodeKind::Edge,
678                    sources: MolIds::One("a".into()),
679                    targets: MolIds::One("b".into()),
680                    label: None,
681                    edge_routing: None,
682                    role: None,
683                    arrow: EdgeArrow::Forward,
684                    color: None,
685                    stroke_width: None,
686                    dashed: false,
687                }),
688            ],
689            layout: None,
690            opts: None,
691            color: None,
692            scale: None,
693            aromatic: None,
694            debug_box: None,
695            debug_align: None,
696            pad: None,
697        };
698        let painted = render(&spec).unwrap();
699        let scene = &painted[0].scene;
700        let gsh = scene
701            .viewports
702            .iter()
703            .find(|vp| vp.id.as_deref() == Some("b"))
704            .expect("GSH mol");
705        let region = gsh
706            .layers
707            .iter()
708            .filter(|l| l.name == LayerName::Shading)
709            .flat_map(|l| l.primitives.iter())
710            .find_map(|p| match p {
711                Primitive::Path {
712                    d, class: Some(c), ..
713                } if c.contains("region") => Some(path_aabb_pts(d)),
714                _ => None,
715            })
716            .expect("region hull");
717        let label = gsh
718            .layers
719            .iter()
720            .filter(|l| l.name == LayerName::Labels)
721            .flat_map(|l| l.primitives.iter())
722            .find_map(|p| match p {
723                Primitive::Path {
724                    d,
725                    data_text: Some(t),
726                    ..
727                } if t.contains("GSH") => Some(path_aabb_pts(d)),
728                _ => None,
729            })
730            .expect("GSH label");
731        let overlap_x = region.0 < label.2 && label.0 < region.2;
732        let overlap_y = region.1 < label.3 && label.1 < region.3;
733        assert!(
734            overlap_x && overlap_y,
735            "region {region:?} must cover GSH label {label:?} (same mol group, leftover not baked)"
736        );
737    }
738
739    fn path_xy(d: &str) -> Vec<(f64, f64)> {
740        let mut nums = Vec::new();
741        let mut cur = String::new();
742        for ch in d.chars() {
743            if ch.is_ascii_digit() || ch == '.' || ch == '-' || ch == '+' || ch == 'e' || ch == 'E'
744            {
745                cur.push(ch);
746            } else if !cur.is_empty() {
747                if let Ok(v) = cur.parse::<f64>() {
748                    nums.push(v);
749                }
750                cur.clear();
751            }
752        }
753        if !cur.is_empty() {
754            if let Ok(v) = cur.parse::<f64>() {
755                nums.push(v);
756            }
757        }
758        nums.chunks(2)
759            .filter_map(|c| (c.len() == 2).then_some((c[0], c[1])))
760            .collect()
761    }
762
763    fn path_aabb_pts(d: &str) -> (f64, f64, f64, f64) {
764        let pts = path_xy(d);
765        let xs = pts.iter().map(|p| p.0);
766        let ys = pts.iter().map(|p| p.1);
767        (
768            xs.clone().fold(f64::INFINITY, f64::min),
769            ys.clone().fold(f64::INFINITY, f64::min),
770            xs.fold(f64::NEG_INFINITY, f64::max),
771            ys.fold(f64::NEG_INFINITY, f64::max),
772        )
773    }
774}