1use std::collections::HashMap;
7
8use serde_json::{json, Value};
9
10use crate::arrows::{
11 edge_anchors, edge_primitives as paint_edge, simplify_route, EdgePaintIn, EdgePrim, ANCHOR_GAP,
12 KINK_PX,
13};
14use crate::debug_box::debug_rect;
15use crate::scene::{LayerName, Primitive, Scene, TextAnchor, Viewport};
16
17use super::{fit, DepictSpec, DocPaint, EdgeNode, EdgeRouting, LabelPos, LayoutOpts, Node};
18
19const EDGE_LABEL_FONT_PX: f64 = 11.0;
20const EDGE_LABEL_PAD: f64 = 4.0;
21const ROW_GAP: f64 = 0.0; pub fn compose_scheme(spec: &DepictSpec, paints: &[DocPaint]) -> Result<Scene, String> {
27 let scene = match spec {
28 DepictSpec::ReactionScheme { layout, .. } => compose_reaction(
29 spec,
30 paints,
31 layout.as_ref().unwrap_or(&LayoutOpts::default()),
32 )?,
33 DepictSpec::Mol(_) | DepictSpec::Group { .. } | DepictSpec::Grid { .. } => {
34 if paints.len() == 1 {
35 paints[0].scene.clone()
36 } else if paints.is_empty() {
37 Scene::empty(0.0, 0.0)
38 } else {
39 place_row(paints, 16.0)
41 }
42 }
43 };
44 let scene = if matches!(spec, DepictSpec::Mol(_)) && paints.len() == 1 {
46 scene
47 } else if paints.is_empty() {
48 scene
49 } else {
50 fit::fit_scene(scene, resolve_compose_pad(spec, paints))
51 };
52 Ok(with_scene_debug_box(spec, paints, scene))
53}
54
55fn resolve_compose_pad(spec: &DepictSpec, paints: &[DocPaint]) -> f64 {
56 let n = spec.mols().len();
58 for i in 0..n {
59 if let Some(p) = spec.resolve_mol_chrome(i).pad {
60 return fit::resolve_viewport_margin(Some(p));
61 }
62 }
63 let _ = paints;
64 fit::VIEWPORT_MARGIN_DEFAULT
65}
66
67fn with_scene_debug_box(spec: &DepictSpec, paints: &[DocPaint], mut scene: Scene) -> Scene {
72 if !spec_wants_debug_box(spec, paints) {
73 return scene;
74 }
75 let already = scene.overlays.iter().any(|p| match p {
76 Primitive::Path { class: Some(c), .. } => c.contains("debug-box-scene"),
77 _ => false,
78 });
79 if already {
80 return scene;
81 }
82 if scene.width > 0.0 && scene.height > 0.0 {
83 scene.overlays.push(debug_rect(
84 scene.x,
85 scene.y,
86 scene.width,
87 scene.height,
88 "debug-box debug-box-scene",
89 ));
90 }
91 scene
92}
93
94fn spec_wants_debug_box(spec: &DepictSpec, paints: &[DocPaint]) -> bool {
95 if paints.iter().any(|p| p.molecule.debug_box) {
96 return true;
97 }
98 let n = spec.mols().len();
99 (0..n).any(|i| spec.resolve_mol_chrome(i).debug_box.unwrap_or(false))
100}
101
102fn compose_reaction(
103 spec: &DepictSpec,
104 paints: &[DocPaint],
105 layout: &LayoutOpts,
106) -> Result<Scene, String> {
107 if paints.is_empty() {
108 return Ok(Scene::empty(0.0, 0.0));
109 }
110
111 let by_id: HashMap<&str, &DocPaint> = paints.iter().map(|p| (p.id.as_str(), p)).collect();
112 let _ = by_id;
113 let sizes: Vec<(String, f64, f64)> = paints
114 .iter()
115 .map(|p| {
116 let (w, h) = scene_size(&p.scene);
117 (p.id.clone(), w, h)
118 })
119 .collect();
120
121 let placement = match layout_scheme(spec, layout, &sizes, paints) {
122 Ok(p) => p,
123 Err(_) => row_placement(&sizes),
124 };
125
126 let mut viewports = Vec::with_capacity(paints.len());
127 let mut overlays = Vec::new();
128 let mut max_r = 0.0_f64;
129 let mut max_b = 0.0_f64;
130
131 for p in paints {
132 let (x, y) = placement
133 .positions
134 .get(p.id.as_str())
135 .copied()
136 .unwrap_or((0.0, 0.0));
137 let (w, h) = scene_size(&p.scene);
138 let mut vp = placed_viewport(&p.scene, &p.id, x, y, w, h);
139 max_r = max_r.max(x + w);
140 max_b = max_b.max(y + h);
141 absorb_mol_document_prims(&mut vp, &p.scene);
142 viewports.push(vp);
143 }
144
145 let vp_boxes: HashMap<&str, (f64, f64, f64, f64)> = viewports
146 .iter()
147 .filter_map(|vp| {
148 let id = vp.id.as_deref()?;
149 Some((id, (vp.x, vp.y, vp.width, vp.height)))
150 })
151 .collect();
152
153 for (i, edge) in spec.edges().iter().enumerate() {
154 let src_id = edge
155 .sources
156 .as_slice()
157 .first()
158 .map(String::as_str)
159 .unwrap_or("");
160 let tgt_id = edge
161 .targets
162 .as_slice()
163 .first()
164 .map(String::as_str)
165 .unwrap_or("");
166 let Some(&src_box) = vp_boxes.get(src_id) else {
167 continue;
168 };
169 let Some(&tgt_box) = vp_boxes.get(tgt_id) else {
170 continue;
171 };
172
173 let route = placement
174 .edge_paths
175 .get(i)
176 .and_then(|p| p.as_ref())
177 .cloned()
178 .filter(|pts| pts.len() >= 2)
179 .unwrap_or_else(|| {
180 let (a, b) = edge_anchors(src_box, tgt_box, ANCHOR_GAP);
181 vec![a, b]
182 });
183 let mut pts = simplify_route(&route, KINK_PX);
184 let route_len: f64 = pts
185 .windows(2)
186 .map(|w| {
187 let (dx, dy) = (w[1].0 - w[0].0, w[1].1 - w[0].1);
188 (dx * dx + dy * dy).sqrt()
189 })
190 .sum();
191 if pts.len() < 2 || route_len < 4.0 {
194 let (a, b) = edge_anchors(src_box, tgt_box, ANCHOR_GAP);
195 pts = vec![a, b];
196 }
197 for &(x, y) in &pts {
198 max_r = max_r.max(x + 8.0);
199 max_b = max_b.max(y + 8.0);
200 }
201
202 let (label_text, label_pos) = resolve_edge_label(spec, edge);
203 let label_pose = placement.edge_labels.get(i).and_then(|p| *p);
204 let paint = EdgePaintIn {
205 pts,
206 arrow: edge.arrow,
207 routing: Some(edge.edge_routing_or(layout)),
208 color: edge.color.clone(),
209 stroke_width: edge.stroke_width,
210 dashed: edge.dashed,
211 label: label_text,
212 label_pos,
213 index: i,
214 curve_catmull: layout.refine_enabled(),
215 label_xy: label_pose.map(|(x, y, _)| (x, y)),
216 label_rotate: label_pose.map(|(_, _, r)| r),
217 };
218 for prim in paint_edge(&paint) {
219 let scene_prim = edge_prim_to_scene(&prim);
220 expand_bounds_prim(&scene_prim, &mut max_r, &mut max_b);
221 overlays.push(scene_prim);
222 }
223 }
224
225 Ok(Scene {
226 width: max_r.max(placement.width.unwrap_or(0.0)),
227 height: max_b.max(placement.height.unwrap_or(0.0)),
228 x: 0.0,
229 y: 0.0,
230 viewports,
231 overlays,
232 halo: Vec::new(),
233 })
234}
235
236fn placed_viewport(src: &Scene, id: &str, x: f64, y: f64, w: f64, h: f64) -> Viewport {
240 let mut vp = src.viewports.first().cloned().unwrap_or(Viewport {
241 id: Some(id.to_string()),
242 x: 0.0,
243 y: 0.0,
244 ox: 0.0,
245 oy: 0.0,
246 width: w,
247 height: h,
248 layers: vec![],
249 });
250 vp.ox += vp.x - src.x;
253 vp.oy += vp.y - src.y;
254 vp.id = Some(id.to_string());
255 vp.x = x;
256 vp.y = y;
257 vp.width = w;
258 vp.height = h;
259 vp
260}
261
262fn absorb_mol_document_prims(vp: &mut Viewport, src: &Scene) {
264 vp.extend_layer(LayerName::Halo, src.halo.clone());
265 vp.extend_layer(LayerName::Overlay, src.overlays.clone());
266}
267
268fn scene_size(scene: &Scene) -> (f64, f64) {
269 if let Some(vp) = scene.viewports.first() {
270 (vp.width.max(scene.width), vp.height.max(scene.height))
271 } else {
272 (scene.width, scene.height)
273 }
274}
275
276fn place_row(paints: &[DocPaint], gap: f64) -> Scene {
277 let sizes: Vec<(String, f64, f64)> = paints
278 .iter()
279 .map(|p| {
280 let (w, h) = scene_size(&p.scene);
281 (p.id.clone(), w, h)
282 })
283 .collect();
284 let max_h = sizes.iter().map(|(_, _, h)| *h).fold(0.0_f64, f64::max);
285 let mut viewports = Vec::new();
286 let mut max_r = 0.0_f64;
287 let mut max_b = 0.0_f64;
288 let mut x = 0.0_f64;
289 for p in paints {
290 let (w, h) = scene_size(&p.scene);
291 let y = (max_h - h) * 0.5;
292 let mut vp = placed_viewport(&p.scene, &p.id, x, y, w, h);
293 max_r = max_r.max(x + w);
294 max_b = max_b.max(y + h);
295 absorb_mol_document_prims(&mut vp, &p.scene);
296 viewports.push(vp);
297 x += w + gap;
298 }
299 Scene {
300 width: max_r,
301 height: max_b,
302 x: 0.0,
303 y: 0.0,
304 viewports,
305 overlays: Vec::new(),
306 halo: Vec::new(),
307 }
308}
309
310struct Placement {
311 positions: HashMap<String, (f64, f64)>,
312 edge_paths: Vec<Option<Vec<(f64, f64)>>>,
313 edge_labels: Vec<Option<(f64, f64, f64)>>,
314 width: Option<f64>,
315 height: Option<f64>,
316}
317
318fn row_placement(sizes: &[(String, f64, f64)]) -> Placement {
319 let max_h = sizes.iter().map(|(_, _, h)| *h).fold(0.0_f64, f64::max);
320 let mut positions = HashMap::new();
321 let mut x = 0.0;
322 for (id, w, h) in sizes {
323 let y = (max_h - h) * 0.5;
324 positions.insert(id.clone(), (x, y));
325 x += w + ROW_GAP;
326 }
327 Placement {
328 positions,
329 edge_paths: vec![],
330 edge_labels: vec![],
331 width: Some(x),
332 height: Some(max_h),
333 }
334}
335
336fn layout_scheme(
337 spec: &DepictSpec,
338 layout: &LayoutOpts,
339 sizes: &[(String, f64, f64)],
340 paints: &[DocPaint],
341) -> Result<Placement, String> {
342 let graph = build_elk_graph(spec, layout, sizes);
343 let laid = crate::elk::layout_json(&serde_json::to_string(&graph).map_err(|e| e.to_string())?)?;
344 let mut placement = parse_elk_placement(spec, &laid, sizes)?;
345 if layout.refine_enabled() {
346 let refined = super::scheme_layout::refine_scheme_edges(
347 spec,
348 layout,
349 &placement.positions,
350 &placement.edge_paths,
351 paints,
352 sizes,
353 );
354 placement.edge_paths = refined.edge_paths;
355 placement.edge_labels = refined.edge_labels;
356 }
357 Ok(placement)
358}
359
360fn build_elk_graph(spec: &DepictSpec, layout: &LayoutOpts, sizes: &[(String, f64, f64)]) -> Value {
361 let opts = crate::elk::scheme_layout_options(crate::elk::DiagramKind::Reaction, layout);
362 let node_opts = crate::elk::scheme_node_layout_options();
363 let children: Vec<Value> = sizes
364 .iter()
365 .map(|(id, w, h)| {
366 json!({
367 "id": id,
368 "width": w,
369 "height": h,
370 "layoutOptions": node_opts.clone(),
371 })
372 })
373 .collect();
374
375 let mut edges = Vec::new();
376 for (i, e) in spec.edges().iter().enumerate() {
377 let eid = format!("e{i}");
378 let mut entry = json!({
379 "id": eid,
380 "sources": e.sources.as_slice(),
381 "targets": e.targets.as_slice(),
382 });
383 if let Some(labels) = elk_edge_labels(spec, e, &format!("e{i}")) {
384 entry["labels"] = labels;
385 }
386 if let Some(r) = e.edge_routing {
387 entry["layoutOptions"] = json!({
388 "elk.edgeRouting": routing_name(r),
389 });
390 }
391 edges.push(entry);
392 }
393
394 json!({
395 "id": "root",
396 "layoutOptions": opts,
397 "children": children,
398 "edges": edges,
399 })
400}
401
402fn routing_name(r: EdgeRouting) -> &'static str {
403 match r {
404 EdgeRouting::Orthogonal => "ORTHOGONAL",
405 EdgeRouting::Polyline => "POLYLINE",
406 EdgeRouting::Splines => "SPLINES",
407 }
408}
409
410fn elk_edge_labels(spec: &DepictSpec, edge: &EdgeNode, edge_id: &str) -> Option<Value> {
411 let (text, pos) = resolve_edge_label(spec, edge);
412 let text = text?.trim().to_string();
413 if text.is_empty() {
414 return None;
415 }
416 let (w, h) = measure_label(&text);
417 let side = match pos.as_deref().unwrap_or("above") {
418 "below" | "right" => "ALWAYS_DOWN",
419 _ => "ALWAYS_UP",
420 };
421 Some(json!([{
422 "id": format!("{edge_id}_lab"),
423 "text": text,
424 "width": w,
425 "height": h,
426 "layoutOptions": {
427 "elk.edgeLabels.placement": "CENTER",
428 "elk.layered.edgeLabels.sideSelection": side,
429 }
430 }]))
431}
432
433fn measure_label(text: &str) -> (f64, f64) {
434 #[cfg(feature = "font")]
435 {
436 use crate::font::{face_metrics, glyph_metrics, FaceStyle};
437 let face = face_metrics(FaceStyle::Regular);
438 let scale = EDGE_LABEL_FONT_PX / face.upem.max(1.0);
439 let mut adv = 0.0;
440 let mut ink_w = 0.0;
441 for ch in text.chars() {
442 if let Some(g) = glyph_metrics(ch, FaceStyle::Regular) {
443 adv += g.advance * scale;
444 ink_w += g.ink_width() * scale;
445 } else {
446 adv += EDGE_LABEL_FONT_PX * 0.5;
447 }
448 }
449 let w = adv.max(ink_w) + EDGE_LABEL_PAD;
450 let typo = (face.ascent - face.descent).abs().max(face.upem * 0.8);
451 let h = typo * scale + EDGE_LABEL_PAD;
452 (w, h)
453 }
454 #[cfg(not(feature = "font"))]
455 {
456 let w = text.len() as f64 * EDGE_LABEL_FONT_PX * 0.55 + EDGE_LABEL_PAD;
457 let h = EDGE_LABEL_FONT_PX + EDGE_LABEL_PAD;
458 (w, h)
459 }
460}
461
462fn parse_elk_placement(
463 spec: &DepictSpec,
464 laid_json: &str,
465 sizes: &[(String, f64, f64)],
466) -> Result<Placement, String> {
467 let laid: Value = serde_json::from_str(laid_json).map_err(|e| e.to_string())?;
468 let mut positions = HashMap::new();
469 for (id, _, _) in sizes {
470 positions.insert(id.clone(), (0.0, 0.0));
471 }
472 if let Some(children) = laid.get("children").and_then(|c| c.as_array()) {
473 for c in children {
474 let Some(id) = c.get("id").and_then(|v| v.as_str()) else {
475 continue;
476 };
477 let x = c.get("x").and_then(|v| v.as_f64()).unwrap_or(0.0);
478 let y = c.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0);
479 positions.insert(id.to_string(), (x, y));
480 }
481 }
482
483 let edges_out = laid.get("edges").and_then(|e| e.as_array());
484 let mut edge_paths = Vec::with_capacity(spec.edges().len());
485 for i in 0..spec.edges().len() {
486 let eid = format!("e{i}");
487 let path = edges_out.and_then(|arr| {
488 arr.iter()
489 .find(|e| e.get("id").and_then(|v| v.as_str()) == Some(eid.as_str()))
490 .and_then(edge_path_from_elk)
491 });
492 edge_paths.push(path);
493 }
494
495 Ok(Placement {
496 positions,
497 edge_paths,
498 edge_labels: vec![],
499 width: laid.get("width").and_then(|v| v.as_f64()),
500 height: laid.get("height").and_then(|v| v.as_f64()),
501 })
502}
503
504fn edge_path_from_elk(edge: &Value) -> Option<Vec<(f64, f64)>> {
505 let sections = edge.get("sections")?.as_array()?;
506 if sections.is_empty() {
507 return None;
508 }
509 let mut path = Vec::new();
510 for sec in sections {
511 let pts = section_points(sec);
512 if pts.is_empty() {
513 continue;
514 }
515 if path.is_empty() {
516 path.extend(pts);
517 } else if pts[0] == *path.last().unwrap() {
518 path.extend(pts.into_iter().skip(1));
519 } else {
520 path.extend(pts);
521 }
522 }
523 if path.len() >= 2 {
524 Some(path)
525 } else {
526 None
527 }
528}
529
530fn section_points(section: &Value) -> Vec<(f64, f64)> {
531 let start = section.get("startPoint").unwrap_or(&Value::Null);
532 let end = section.get("endPoint").unwrap_or(&Value::Null);
533 let mut pts = vec![(
534 start.get("x").and_then(|v| v.as_f64()).unwrap_or(0.0),
535 start.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0),
536 )];
537 if let Some(bends) = section.get("bendPoints").and_then(|b| b.as_array()) {
538 for bp in bends {
539 pts.push((
540 bp.get("x").and_then(|v| v.as_f64()).unwrap_or(0.0),
541 bp.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0),
542 ));
543 }
544 }
545 pts.push((
546 end.get("x").and_then(|v| v.as_f64()).unwrap_or(0.0),
547 end.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0),
548 ));
549 let mut cleaned = Vec::new();
550 for p in pts {
551 if cleaned
552 .last()
553 .map(|&(lx, ly): &(f64, f64)| (p.0 - lx).abs() > 1e-6 || (p.1 - ly).abs() > 1e-6)
554 .unwrap_or(true)
555 {
556 cleaned.push(p);
557 }
558 }
559 cleaned
560}
561
562fn resolve_edge_label(spec: &DepictSpec, edge: &EdgeNode) -> (Option<String>, Option<String>) {
563 let Some(ref lab) = edge.label else {
564 return (None, None);
565 };
566 let placements = lab.placements();
567 let Some((id, pos)) = placements.first() else {
568 return (None, None);
569 };
570 let text = match spec.node_by_id(id.trim()) {
571 Some(Node::Text(t)) => Some(t.text.clone()),
572 None if !id.trim().is_empty() && spec.node_by_id(id.trim()).is_none() => {
576 None
578 }
579 _ => None,
580 };
581 let pos = Some(match pos {
582 LabelPos::Above => "above".into(),
583 LabelPos::Below => "below".into(),
584 LabelPos::Left => "left".into(),
585 LabelPos::Right => "right".into(),
586 });
587 (text, pos)
588}
589
590fn edge_prim_to_scene(p: &EdgePrim) -> Primitive {
591 match p {
592 EdgePrim::Path {
593 d,
594 stroke,
595 fill,
596 stroke_width,
597 stroke_dasharray,
598 class,
599 } => Primitive::Path {
600 d: d.clone(),
601 stroke: if stroke == "none" {
602 None
603 } else {
604 Some(stroke.clone())
605 },
606 fill: if fill == "none" {
607 None
608 } else {
609 Some(fill.clone())
610 },
611 stroke_width: *stroke_width,
612 opacity: 1.0,
613 stroke_dasharray: stroke_dasharray.clone(),
614 stroke_linecap: None,
615 class: Some(class.clone()),
616 data_text: None,
617 },
618 EdgePrim::Text {
619 x,
620 y,
621 text,
622 fill,
623 font_size,
624 anchor,
625 class,
626 rotate,
627 } => Primitive::Text {
628 x: *x,
629 y: *y,
630 text: text.clone(),
631 fill: fill.clone(),
632 font_size: *font_size,
633 anchor: match anchor.as_str() {
634 "start" => TextAnchor::Start,
635 "end" => TextAnchor::End,
636 _ => TextAnchor::Middle,
637 },
638 class: Some(class.clone()),
639 rotate: if rotate.abs() > 1e-6 {
640 Some(*rotate)
641 } else {
642 None
643 },
644 },
645 }
646}
647
648#[cfg(test)]
649fn translate_prim(p: &Primitive, dx: f64, dy: f64) -> Primitive {
650 match p {
651 Primitive::Path {
652 d,
653 stroke,
654 fill,
655 stroke_width,
656 opacity,
657 stroke_dasharray,
658 stroke_linecap,
659 class,
660 data_text,
661 } => Primitive::Path {
662 d: d.clone(),
663 stroke: stroke.clone(),
664 fill: fill.clone(),
665 stroke_width: *stroke_width,
666 opacity: *opacity,
667 stroke_dasharray: stroke_dasharray.clone(),
668 stroke_linecap: stroke_linecap.clone(),
669 class: class.clone(),
670 data_text: data_text.clone(),
671 },
672 Primitive::Circle {
673 cx,
674 cy,
675 r,
676 fill,
677 stroke,
678 stroke_width,
679 opacity,
680 class,
681 } => Primitive::Circle {
682 cx: cx + dx,
683 cy: cy + dy,
684 r: *r,
685 fill: fill.clone(),
686 stroke: stroke.clone(),
687 stroke_width: *stroke_width,
688 opacity: *opacity,
689 class: class.clone(),
690 },
691 Primitive::Text {
692 x,
693 y,
694 text,
695 fill,
696 font_size,
697 anchor,
698 class,
699 rotate,
700 } => Primitive::Text {
701 x: x + dx,
702 y: y + dy,
703 text: text.clone(),
704 fill: fill.clone(),
705 font_size: *font_size,
706 anchor: *anchor,
707 class: class.clone(),
708 rotate: *rotate,
709 },
710 }
711}
712
713fn expand_bounds_prim(p: &Primitive, max_r: &mut f64, max_b: &mut f64) {
714 match p {
715 Primitive::Text { x, y, .. } => {
716 *max_r = max_r.max(*x + 12.0);
717 *max_b = max_b.max(*y + 12.0);
718 }
719 Primitive::Path { d, .. } => {
720 for (x, y) in path_coords(d) {
721 *max_r = max_r.max(x + 8.0);
722 *max_b = max_b.max(y + 8.0);
723 }
724 }
725 Primitive::Circle { cx, cy, r, .. } => {
726 *max_r = max_r.max(cx + r + 4.0);
727 *max_b = max_b.max(cy + r + 4.0);
728 }
729 }
730}
731
732fn path_coords(d: &str) -> Vec<(f64, f64)> {
733 let mut nums = Vec::new();
734 let mut cur = String::new();
735 for c in d.chars() {
736 if c.is_ascii_digit() || c == '.' || c == '-' || c == '+' || c == 'e' || c == 'E' {
737 cur.push(c);
738 } else if !cur.is_empty() {
739 if let Ok(v) = cur.parse::<f64>() {
740 nums.push(v);
741 }
742 cur.clear();
743 }
744 }
745 if !cur.is_empty() {
746 if let Ok(v) = cur.parse::<f64>() {
747 nums.push(v);
748 }
749 }
750 let mut out = Vec::new();
751 let mut i = 0;
752 while i + 1 < nums.len() {
753 out.push((nums[i], nums[i + 1]));
754 i += 2;
755 }
756 out
757}
758
759#[cfg(test)]
760mod tests {
761 use super::*;
762 use crate::arrows::EdgePrim;
763 use crate::doc::{EdgeArrow, EdgeNodeKind, MolIds, MolNode, TextNode, TextNodeKind};
764 use crate::scene::{AtomIn, Layer, LayerName, MoleculeIn, TextAnchor};
765
766 fn paint(id: &str, w: f64, h: f64) -> DocPaint {
767 DocPaint {
768 id: id.into(),
769 frame_json: String::new(),
770 molecule: MoleculeIn {
771 id: Some(id.into()),
772 atoms: vec![AtomIn {
773 index: 0,
774 element: Some("C".into()),
775 z: Some(6),
776 x: 10.0,
777 y: 10.0,
778 label: None,
779 charge: 0,
780 mapno: None,
781 }],
782 bonds: vec![],
783 color: None,
784 atom_shade: None,
785 bond_shade: None,
786 shade_vmin: None,
787 shade_vmax: None,
788 scale: 1.0,
789 weight: 1.0,
790 aromatic: Default::default(),
791 debug_box: false,
792 debug_align: false,
793 align_debug: None,
794 ..Default::default()
795 },
796 scene: Scene {
797 width: w,
798 height: h,
799 x: 0.0,
800 y: 0.0,
801 viewports: vec![Viewport {
802 id: Some(id.into()),
803 x: 0.0,
804 y: 0.0,
805 ox: 0.0,
806 oy: 0.0,
807 width: w,
808 height: h,
809 layers: vec![Layer {
810 name: LayerName::Bonds,
811 primitives: vec![],
812 }],
813 }],
814 overlays: vec![],
815 halo: vec![],
816 },
817 }
818 }
819
820 #[test]
821 fn compose_two_mol_scheme_has_overlay() {
822 let spec = DepictSpec::ReactionScheme {
823 id: None,
824 children: vec![
825 Node::Mol(MolNode {
826 id: Some("A".into()),
827 smiles: Some("CCO".into()),
828 ..Default::default()
829 }),
830 Node::Text(TextNode {
831 type_: TextNodeKind::Text,
832 id: Some("lab".into()),
833 text: "ox".into(),
834 color: None,
835 scale: None,
836 opts: None,
837 }),
838 Node::Edge(EdgeNode {
839 type_: EdgeNodeKind::Edge,
840 sources: MolIds::One("A".into()),
841 targets: MolIds::One("B".into()),
842 label: Some(crate::doc::Label::Id("lab".into())),
843 edge_routing: None,
844 role: None,
845 arrow: EdgeArrow::Forward,
846 color: None,
847 stroke_width: None,
848 dashed: false,
849 }),
850 Node::Mol(MolNode {
851 id: Some("B".into()),
852 smiles: Some("CC=O".into()),
853 ..Default::default()
854 }),
855 ],
856 layout: Some(LayoutOpts {
857 edge_routing: Some(EdgeRouting::Orthogonal),
858 refine: Some(false),
859 ..Default::default()
860 }),
861 opts: None,
862 color: None,
863 scale: None,
864 aromatic: None,
865 debug_box: None,
866 debug_align: None,
867 pad: None,
868 };
869 let paints = vec![paint("A", 80.0, 60.0), paint("B", 80.0, 60.0)];
870 let scene = compose_scheme(&spec, &paints).expect("compose");
871 assert_eq!(scene.viewports.len(), 2);
872 assert!(
873 !scene.overlays.is_empty(),
874 "expected edge overlays, got none"
875 );
876 assert!(scene.width > 80.0);
877 }
878
879 fn paint_shifted(id: &str, w: f64, h: f64, ox: f64, oy: f64, cx: f64, cy: f64) -> DocPaint {
880 let mut p = paint(id, w, h);
881 let vp = p.scene.viewports.first_mut().unwrap();
882 vp.ox = ox;
883 vp.oy = oy;
884 vp.layers[0].primitives.push(Primitive::Circle {
885 cx,
886 cy,
887 r: 2.0,
888 fill: Some("#000".into()),
889 stroke: None,
890 stroke_width: 0.0,
891 opacity: 1.0,
892 class: None,
893 });
894 p
895 }
896
897 #[test]
898 fn scheme_group_transform_keeps_fit_origin_in_local_space() {
899 let a = paint_shifted("A", 80.0, 60.0, -20.0, -25.0, 50.0, 55.0);
902 let b = paint_shifted("B", 80.0, 60.0, -20.0, -25.0, 50.0, 55.0);
903 let spec = DepictSpec::ReactionScheme {
904 id: None,
905 children: vec![
906 Node::Mol(MolNode {
907 id: Some("A".into()),
908 smiles: Some("C".into()),
909 ..Default::default()
910 }),
911 Node::Mol(MolNode {
912 id: Some("B".into()),
913 smiles: Some("O".into()),
914 ..Default::default()
915 }),
916 Node::Edge(EdgeNode {
917 type_: EdgeNodeKind::Edge,
918 sources: MolIds::One("A".into()),
919 targets: MolIds::One("B".into()),
920 label: None,
921 edge_routing: None,
922 role: None,
923 arrow: EdgeArrow::Forward,
924 color: None,
925 stroke_width: None,
926 dashed: false,
927 }),
928 ],
929 layout: Some(LayoutOpts {
930 layer_spacing: Some(40.0),
931 refine: Some(false),
932 ..Default::default()
933 }),
934 opts: None,
935 color: None,
936 scale: None,
937 aromatic: None,
938 debug_box: None,
939 debug_align: None,
940 pad: None,
941 };
942 let scene = compose_scheme(&spec, &[a, b]).expect("compose");
943 let vp = &scene.viewports[0];
944 let cy = vp.layers[0]
945 .primitives
946 .iter()
947 .find_map(|p| match p {
948 Primitive::Circle { cy, .. } => Some(*cy),
949 _ => None,
950 })
951 .expect("circle");
952 assert!(
955 (cy - 55.0).abs() < 1e-6,
956 "local cy {cy} should stay at paint 55"
957 );
958 let ink_y = vp.y + vp.oy + cy;
959 let mut shaft_y = None;
960 for p in &scene.overlays {
961 if let Primitive::Path {
962 d, class: Some(c), ..
963 } = p
964 {
965 if c.contains("edge") && !c.contains("head") {
966 let ys: Vec<f64> = super::path_coords(d).into_iter().map(|(_, y)| y).collect();
967 if ys.len() >= 2 {
968 shaft_y = Some((ys[0] + ys[1]) * 0.5);
969 break;
970 }
971 }
972 }
973 }
974 let shaft_y = shaft_y.expect("shaft");
975 assert!(
976 (shaft_y - (vp.y + vp.height * 0.5)).abs() < 8.0,
977 "shaft y {shaft_y} vs box mid {}",
978 vp.y + vp.height * 0.5
979 );
980 assert!(
982 (ink_y - shaft_y).abs() < vp.height * 0.5,
983 "ink y {ink_y} far from shaft {shaft_y}"
984 );
985 }
986
987 #[test]
988 fn live_scheme_arrow_aligns_with_mol_ink() {
989 let spec = DepictSpec::ReactionScheme {
990 id: None,
991 children: vec![
992 Node::Mol(MolNode {
993 id: Some("A".into()),
994 smiles: Some("CCO".into()),
995 ..Default::default()
996 }),
997 Node::Mol(MolNode {
998 id: Some("B".into()),
999 smiles: Some("CC=O".into()),
1000 ..Default::default()
1001 }),
1002 Node::Edge(EdgeNode {
1003 type_: EdgeNodeKind::Edge,
1004 sources: MolIds::One("A".into()),
1005 targets: MolIds::One("B".into()),
1006 label: None,
1007 edge_routing: None,
1008 role: None,
1009 arrow: EdgeArrow::Forward,
1010 color: None,
1011 stroke_width: None,
1012 dashed: false,
1013 }),
1014 ],
1015 layout: Some(LayoutOpts {
1016 layer_spacing: Some(40.0),
1017 refine: Some(false),
1018 ..Default::default()
1019 }),
1020 opts: None,
1021 color: None,
1022 scale: None,
1023 aromatic: None,
1024 debug_box: None,
1025 debug_align: None,
1026 pad: None,
1027 };
1028 let out = crate::doc::render(&spec).expect("render");
1029 assert_eq!(out.len(), 1);
1030 let scene = &out[0].scene;
1031 let mut ink_y = Vec::new();
1032 for vp in &scene.viewports {
1033 for layer in &vp.layers {
1034 for p in &layer.primitives {
1035 match p {
1036 Primitive::Circle { cy, .. } => ink_y.push(vp.y + vp.oy + *cy),
1037 Primitive::Path { d, .. } => {
1038 ink_y.extend(
1039 super::path_coords(d)
1040 .into_iter()
1041 .map(|(_, y)| vp.y + vp.oy + y),
1042 );
1043 }
1044 Primitive::Text { y, .. } => ink_y.push(vp.y + vp.oy + *y),
1045 }
1046 }
1047 }
1048 }
1049 let ink_min = ink_y.iter().copied().fold(f64::INFINITY, f64::min);
1050 let ink_max = ink_y.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1051 let mut shaft_y = None;
1052 for p in &scene.overlays {
1053 if let Primitive::Path {
1054 d, class: Some(c), ..
1055 } = p
1056 {
1057 if c.contains("edge") && !c.contains("head") {
1058 let ys: Vec<f64> = super::path_coords(d).into_iter().map(|(_, y)| y).collect();
1059 if ys.len() >= 2 {
1060 shaft_y = Some((ys[0] + ys[1]) * 0.5);
1061 break;
1062 }
1063 }
1064 }
1065 }
1066 let shaft_y = shaft_y.expect("shaft");
1067 assert!(
1068 shaft_y >= ink_min - 2.0 && shaft_y <= ink_max + 2.0,
1069 "shaft y {shaft_y} outside mol ink {ink_min}..{ink_max}"
1070 );
1071 }
1072
1073 #[test]
1074 fn compose_empty_and_group_row() {
1075 let empty = compose_scheme(
1076 &DepictSpec::ReactionScheme {
1077 id: None,
1078 children: vec![],
1079 layout: None,
1080 opts: None,
1081 color: None,
1082 scale: None,
1083 aromatic: None,
1084 debug_box: None,
1085 debug_align: None,
1086 pad: None,
1087 },
1088 &[],
1089 )
1090 .unwrap();
1091 assert!(empty.viewports.is_empty());
1092
1093 let group = DepictSpec::Group {
1094 id: None,
1095 children: vec![
1096 Node::Mol(MolNode {
1097 id: Some("a".into()),
1098 smiles: Some("C".into()),
1099 ..Default::default()
1100 }),
1101 Node::Mol(MolNode {
1102 id: Some("b".into()),
1103 smiles: Some("O".into()),
1104 ..Default::default()
1105 }),
1106 ],
1107 align: false,
1108 opts: None,
1109 color: None,
1110 scale: None,
1111 aromatic: None,
1112 debug_box: None,
1113 debug_align: None,
1114 pad: None,
1115 };
1116 let scene =
1117 compose_scheme(&group, &[paint("a", 40.0, 30.0), paint("b", 50.0, 30.0)]).unwrap();
1118 assert_eq!(scene.viewports.len(), 2);
1119 assert!(scene.viewports[1].x > scene.viewports[0].x);
1120 }
1121
1122 #[test]
1123 fn translate_and_measure_helpers() {
1124 let (w, h) = measure_label("ADH");
1125 assert!(w > 10.0 && h > 5.0);
1126
1127 let p = Primitive::Circle {
1128 cx: 1.0,
1129 cy: 2.0,
1130 r: 3.0,
1131 fill: Some("#000".into()),
1132 stroke: None,
1133 stroke_width: 0.0,
1134 opacity: 1.0,
1135 class: None,
1136 };
1137 let t = translate_prim(&p, 10.0, 20.0);
1138 match t {
1139 Primitive::Circle { cx, cy, .. } => {
1140 assert!((cx - 11.0).abs() < 1e-9);
1141 assert!((cy - 22.0).abs() < 1e-9);
1142 }
1143 _ => panic!("expected circle"),
1144 }
1145
1146 let path = Primitive::Path {
1147 d: "M 0.00 0.00 L 10.00 5.00".into(),
1148 stroke: Some("#222".into()),
1149 fill: None,
1150 stroke_width: 1.0,
1151 opacity: 1.0,
1152 stroke_dasharray: None,
1153 stroke_linecap: None,
1154 class: Some("edge".into()),
1155 data_text: None,
1156 };
1157 let shifted = translate_prim(&path, 1.0, 2.0);
1158 match shifted {
1159 Primitive::Path { d, .. } => {
1160 assert_eq!(
1161 d, "M 0.00 0.00 L 10.00 5.00",
1162 "paths are not moved by rewriting d"
1163 );
1164 }
1165 _ => panic!("expected path"),
1166 }
1167
1168 let text = Primitive::Text {
1169 x: 0.0,
1170 y: 0.0,
1171 text: "hi".into(),
1172 fill: "#000".into(),
1173 font_size: 11.0,
1174 anchor: TextAnchor::Middle,
1175 class: None,
1176 rotate: None,
1177 };
1178 match translate_prim(&text, 5.0, 6.0) {
1179 Primitive::Text { x, y, .. } => {
1180 assert!((x - 5.0).abs() < 1e-9);
1181 assert!((y - 6.0).abs() < 1e-9);
1182 }
1183 _ => panic!("expected text"),
1184 }
1185 }
1186
1187 #[test]
1188 fn edge_prim_mapping_and_path_coords() {
1189 let path = edge_prim_to_scene(&EdgePrim::Path {
1190 d: "M 1 2".into(),
1191 stroke: "none".into(),
1192 fill: "#222".into(),
1193 stroke_width: 0.0,
1194 stroke_dasharray: None,
1195 class: "head".into(),
1196 });
1197 match path {
1198 Primitive::Path {
1199 stroke,
1200 fill,
1201 class,
1202 ..
1203 } => {
1204 assert!(stroke.is_none());
1205 assert_eq!(fill.as_deref(), Some("#222"));
1206 assert_eq!(class.as_deref(), Some("head"));
1207 }
1208 _ => panic!("path"),
1209 }
1210 let txt = edge_prim_to_scene(&EdgePrim::Text {
1211 x: 1.0,
1212 y: 2.0,
1213 text: "L".into(),
1214 fill: "#222".into(),
1215 font_size: 11.0,
1216 anchor: "start".into(),
1217 class: "label".into(),
1218 rotate: 0.0,
1219 });
1220 match txt {
1221 Primitive::Text { anchor, .. } => assert_eq!(anchor, TextAnchor::Start),
1222 _ => panic!("text"),
1223 }
1224 let pts = path_coords("M 0 0 L 3 4");
1225 assert_eq!(pts.len(), 2);
1226 }
1227
1228 #[test]
1229 fn section_and_edge_path_parse() {
1230 let sec = serde_json::json!({
1231 "startPoint": {"x": 0.0, "y": 0.0},
1232 "bendPoints": [{"x": 10.0, "y": 0.0}],
1233 "endPoint": {"x": 10.0, "y": 10.0}
1234 });
1235 let pts = section_points(&sec);
1236 assert_eq!(pts.len(), 3);
1237 let edge = serde_json::json!({
1238 "sections": [sec]
1239 });
1240 let path = edge_path_from_elk(&edge).unwrap();
1241 assert!(path.len() >= 2);
1242 }
1243
1244 #[test]
1245 fn row_placement_and_halo_and_skip_edges() {
1246 let p = row_placement(&[("a".into(), 10.0, 20.0), ("b".into(), 12.0, 40.0)]);
1247 assert!(p.positions["a"].1 > 0.0); assert_eq!(p.positions["b"].1, 0.0);
1249
1250 let mut a = paint("A", 50.0, 40.0);
1251 a.scene.halo.push(Primitive::Circle {
1252 cx: 1.0,
1253 cy: 1.0,
1254 r: 2.0,
1255 fill: Some("#fff".into()),
1256 stroke: None,
1257 stroke_width: 0.0,
1258 opacity: 1.0,
1259 class: Some("halo".into()),
1260 });
1261 let bare = DocPaint {
1263 id: "Z".into(),
1264 frame_json: String::new(),
1265 molecule: a.molecule.clone(),
1266 scene: Scene {
1267 width: 30.0,
1268 height: 20.0,
1269 x: 0.0,
1270 y: 0.0,
1271 viewports: vec![],
1272 overlays: vec![],
1273 halo: vec![],
1274 },
1275 };
1276 let _ = scene_size(&bare.scene);
1277
1278 let spec = DepictSpec::ReactionScheme {
1279 id: None,
1280 children: vec![
1281 Node::Mol(MolNode {
1282 id: Some("A".into()),
1283 smiles: Some("C".into()),
1284 ..Default::default()
1285 }),
1286 Node::Mol(MolNode {
1287 id: Some("B".into()),
1288 smiles: Some("O".into()),
1289 ..Default::default()
1290 }),
1291 Node::Text(TextNode {
1292 type_: TextNodeKind::Text,
1293 id: Some("lab".into()),
1294 text: " ".into(), color: None,
1296 scale: None,
1297 opts: None,
1298 }),
1299 Node::Edge(EdgeNode {
1300 type_: EdgeNodeKind::Edge,
1301 sources: MolIds::One("A".into()),
1302 targets: MolIds::One("B".into()),
1303 label: Some(crate::doc::Label::Placed(crate::doc::LabelPlacement {
1304 id: "lab".into(),
1305 pos: Some(LabelPos::Below),
1306 })),
1307 edge_routing: Some(EdgeRouting::Splines),
1308 role: None,
1309 arrow: EdgeArrow::Line,
1310 color: Some("#06c".into()),
1311 stroke_width: Some(2.0),
1312 dashed: true,
1313 }),
1314 Node::Edge(EdgeNode {
1316 type_: EdgeNodeKind::Edge,
1317 sources: MolIds::One("A".into()),
1318 targets: MolIds::One("missing".into()),
1319 label: None,
1320 edge_routing: None,
1321 role: None,
1322 arrow: EdgeArrow::Forward,
1323 color: None,
1324 stroke_width: None,
1325 dashed: false,
1326 }),
1327 ],
1328 layout: Some(LayoutOpts {
1329 edge_routing: Some(EdgeRouting::Polyline),
1330 algorithm: Some(crate::doc::LayoutAlgorithm::Layered),
1331 direction: Some(crate::doc::LayoutDirection::Down),
1332 node_spacing: Some(16.0),
1333 layer_spacing: Some(8.0),
1334 refine: Some(false),
1335 }),
1336 opts: None,
1337 color: None,
1338 scale: None,
1339 aromatic: None,
1340 debug_box: None,
1341 debug_align: None,
1342 pad: None,
1343 };
1344 let scene = compose_scheme(&spec, &[a, paint("B", 50.0, 40.0)]).unwrap();
1345 assert!(
1346 scene.viewports.iter().any(|vp| vp
1347 .layers
1348 .iter()
1349 .any(|l| l.name == LayerName::Halo && !l.primitives.is_empty())),
1350 "mol halo rides the viewport group, not a rewritten document path"
1351 );
1352 assert!(!scene.overlays.is_empty());
1353 assert_eq!(routing_name(EdgeRouting::Orthogonal), "ORTHOGONAL");
1354 assert_eq!(routing_name(EdgeRouting::Splines), "SPLINES");
1355
1356 let (t, _) = resolve_edge_label(
1358 &spec,
1359 &EdgeNode {
1360 type_: EdgeNodeKind::Edge,
1361 sources: MolIds::One("A".into()),
1362 targets: MolIds::One("B".into()),
1363 label: None,
1364 edge_routing: None,
1365 role: None,
1366 arrow: EdgeArrow::Forward,
1367 color: None,
1368 stroke_width: None,
1369 dashed: false,
1370 },
1371 );
1372 assert!(t.is_none());
1373
1374 let empty_edge = serde_json::json!({"sections": []});
1375 assert!(edge_path_from_elk(&empty_edge).is_none());
1376 let multi = serde_json::json!({
1377 "sections": [
1378 {
1379 "startPoint": {"x": 0.0, "y": 0.0},
1380 "endPoint": {"x": 5.0, "y": 0.0}
1381 },
1382 {
1383 "startPoint": {"x": 5.0, "y": 0.0},
1384 "bendPoints": [{"x": 5.0, "y": 5.0}],
1385 "endPoint": {"x": 10.0, "y": 5.0}
1386 }
1387 ]
1388 });
1389 assert!(edge_path_from_elk(&multi).unwrap().len() >= 3);
1390
1391 let mut mr = 0.0;
1392 let mut mb = 0.0;
1393 expand_bounds_prim(
1394 &Primitive::Circle {
1395 cx: 9.0,
1396 cy: 9.0,
1397 r: 2.0,
1398 fill: None,
1399 stroke: None,
1400 stroke_width: 0.0,
1401 opacity: 1.0,
1402 class: None,
1403 },
1404 &mut mr,
1405 &mut mb,
1406 );
1407 assert!(mr > 9.0);
1408 }
1409
1410 #[test]
1411 fn compose_empty_mol_and_anchors() {
1412 let mol = DepictSpec::Mol(MolNode {
1413 smiles: Some("C".into()),
1414 cxsmiles: None,
1415 molfile: None,
1416 id: None,
1417 label: None,
1418 name: None,
1419 atom_number: None,
1420 atom_label: None,
1421 region: None,
1422 circle: None,
1423 callout: None,
1424 star_labels: None,
1425 align_to: None,
1426 opts: None,
1427 color: None,
1428 scale: None,
1429 weight: None,
1430 halo: None,
1431 aromatic: None,
1432 debug_box: None,
1433 debug_align: None,
1434 pad: None,
1435 shade: None,
1436 ..Default::default()
1437 });
1438 let empty = compose_scheme(&mol, &[]).unwrap();
1439 assert!(empty.viewports.is_empty());
1440
1441 assert_eq!(routing_name(EdgeRouting::Polyline), "POLYLINE");
1442 match edge_prim_to_scene(&EdgePrim::Text {
1443 x: 0.0,
1444 y: 0.0,
1445 text: "x".into(),
1446 fill: "#000".into(),
1447 font_size: 10.0,
1448 anchor: "end".into(),
1449 class: "c".into(),
1450 rotate: 0.0,
1451 }) {
1452 Primitive::Text {
1453 anchor: TextAnchor::End,
1454 ..
1455 } => {}
1456 _ => panic!("end anchor"),
1457 }
1458
1459 let mut a = paint("A", 40.0, 30.0);
1460 a.scene.halo.push(Primitive::Text {
1461 x: 0.0,
1462 y: 0.0,
1463 text: "h".into(),
1464 fill: "#fff".into(),
1465 font_size: 8.0,
1466 anchor: TextAnchor::Start,
1467 class: None,
1468 rotate: None,
1469 });
1470 let row = place_row(&[a, paint("B", 40.0, 30.0)], 8.0);
1471 assert_eq!(row.viewports.len(), 2);
1472 assert!(
1473 row.viewports.iter().any(|vp| vp
1474 .layers
1475 .iter()
1476 .any(|l| l.name == LayerName::Halo && !l.primitives.is_empty())),
1477 "row halo stays on the mol group"
1478 );
1479
1480 let rel = translate_prim(
1482 &Primitive::Path {
1483 d: "m 1 2 l 3 4".into(),
1484 stroke: None,
1485 fill: None,
1486 stroke_width: 1.0,
1487 opacity: 1.0,
1488 stroke_dasharray: None,
1489 stroke_linecap: None,
1490 class: None,
1491 data_text: None,
1492 },
1493 10.0,
1494 10.0,
1495 );
1496 match rel {
1497 Primitive::Path { d, .. } => {
1498 assert!(d.contains('m') || d.contains('l') || d.contains('1'))
1499 }
1500 _ => panic!("path"),
1501 }
1502
1503 let (none_t, _) = resolve_edge_label(
1504 &DepictSpec::ReactionScheme {
1505 id: None,
1506 children: vec![],
1507 layout: None,
1508 opts: None,
1509 color: None,
1510 scale: None,
1511 aromatic: None,
1512 debug_box: None,
1513 debug_align: None,
1514 pad: None,
1515 },
1516 &EdgeNode {
1517 type_: EdgeNodeKind::Edge,
1518 sources: MolIds::One("A".into()),
1519 targets: MolIds::One("B".into()),
1520 label: Some(crate::doc::Label::Items(vec![])),
1521 edge_routing: None,
1522 role: None,
1523 arrow: EdgeArrow::Forward,
1524 color: None,
1525 stroke_width: None,
1526 dashed: false,
1527 },
1528 );
1529 assert!(none_t.is_none());
1530
1531 let joined = edge_path_from_elk(&serde_json::json!({
1532 "sections": [
1533 {"startPoint":{"x":0,"y":0},"endPoint":{"x":1,"y":0}},
1534 {"startPoint":{"x":2,"y":0},"endPoint":{"x":3,"y":0}}
1535 ]
1536 }))
1537 .unwrap();
1538 assert!(joined.len() >= 3);
1539 }
1540
1541 #[test]
1542 fn compose_mol_root_passthrough() {
1543 let paints = vec![paint("m0", 50.0, 40.0)];
1544 let spec = DepictSpec::Mol(MolNode {
1545 smiles: Some("C".into()),
1546 cxsmiles: None,
1547 molfile: None,
1548 id: Some("m0".into()),
1549 label: None,
1550 name: None,
1551 atom_number: None,
1552 atom_label: None,
1553 region: None,
1554 circle: None,
1555 callout: None,
1556 star_labels: None,
1557 align_to: None,
1558 opts: None,
1559 color: None,
1560 scale: None,
1561 weight: None,
1562 halo: None,
1563 aromatic: None,
1564 debug_box: None,
1565 debug_align: None,
1566 pad: None,
1567 shade: None,
1568 ..Default::default()
1569 });
1570 let scene = compose_scheme(&spec, &paints).unwrap();
1571 assert_eq!(scene.viewports.len(), 1);
1572 assert!((scene.width - 50.0).abs() < 1e-9 || scene.viewports[0].width == 50.0);
1573 }
1574
1575 #[test]
1576 fn refined_scheme_paints_catmull_shaft() {
1577 let spec = DepictSpec::ReactionScheme {
1578 id: None,
1579 children: vec![
1580 Node::Mol(MolNode {
1581 id: Some("A".into()),
1582 smiles: Some("CCO".into()),
1583 ..Default::default()
1584 }),
1585 Node::Edge(EdgeNode {
1586 type_: EdgeNodeKind::Edge,
1587 sources: MolIds::One("A".into()),
1588 targets: MolIds::One("B".into()),
1589 label: None,
1590 edge_routing: None,
1591 role: None,
1592 arrow: EdgeArrow::Forward,
1593 color: None,
1594 stroke_width: None,
1595 dashed: false,
1596 }),
1597 Node::Mol(MolNode {
1598 id: Some("B".into()),
1599 smiles: Some("CC=O".into()),
1600 ..Default::default()
1601 }),
1602 ],
1603 layout: Some(LayoutOpts {
1604 refine: Some(true),
1605 ..Default::default()
1606 }),
1607 opts: None,
1608 color: None,
1609 scale: None,
1610 aromatic: None,
1611 debug_box: None,
1612 debug_align: None,
1613 pad: None,
1614 };
1615 let paints = vec![paint("A", 120.0, 80.0), paint("B", 120.0, 80.0)];
1616 let scene = compose_scheme(&spec, &paints).expect("compose");
1617 assert_eq!(scene.viewports.len(), 2);
1618 let has_c = scene.overlays.iter().any(|p| match p {
1619 Primitive::Path {
1620 d, class: Some(c), ..
1621 } if c.contains("edge") => d.contains('C'),
1622 _ => false,
1623 });
1624 let has_shaft = scene.overlays.iter().any(|p| match p {
1625 Primitive::Path { class: Some(c), .. } => c.contains("edge"),
1626 _ => false,
1627 });
1628 assert!(has_shaft, "expected an edge overlay");
1629 let _ = has_c;
1631 let xa = scene.viewports[0].x;
1632 let xb = scene.viewports[1].x;
1633 assert!(
1634 (xa - xb).abs() > 1.0,
1635 "mols should keep distinct ELK x: {xa} vs {xb}"
1636 );
1637 }
1638
1639 #[test]
1640 fn refine_keeps_elk_mol_positions() {
1641 let children = vec![
1642 Node::Mol(MolNode {
1643 id: Some("A".into()),
1644 smiles: Some("CCO".into()),
1645 ..Default::default()
1646 }),
1647 Node::Edge(EdgeNode {
1648 type_: EdgeNodeKind::Edge,
1649 sources: MolIds::One("A".into()),
1650 targets: MolIds::One("B".into()),
1651 label: None,
1652 edge_routing: None,
1653 role: None,
1654 arrow: EdgeArrow::Forward,
1655 color: None,
1656 stroke_width: None,
1657 dashed: false,
1658 }),
1659 Node::Mol(MolNode {
1660 id: Some("B".into()),
1661 smiles: Some("CC=O".into()),
1662 ..Default::default()
1663 }),
1664 ];
1665 let paints = vec![paint("A", 120.0, 80.0), paint("B", 120.0, 80.0)];
1666 let vanilla = DepictSpec::ReactionScheme {
1667 id: None,
1668 children: children.clone(),
1669 layout: Some(LayoutOpts {
1670 refine: Some(false),
1671 ..Default::default()
1672 }),
1673 opts: None,
1674 color: None,
1675 scale: None,
1676 aromatic: None,
1677 debug_box: None,
1678 debug_align: None,
1679 pad: None,
1680 };
1681 let refined = DepictSpec::ReactionScheme {
1682 id: None,
1683 children: children.clone(),
1684 layout: Some(LayoutOpts {
1685 refine: Some(true),
1686 ..Default::default()
1687 }),
1688 opts: None,
1689 color: None,
1690 scale: None,
1691 aromatic: None,
1692 debug_box: None,
1693 debug_align: None,
1694 pad: None,
1695 };
1696 let a = compose_scheme(&vanilla, &paints).expect("elk");
1697 let b = compose_scheme(&refined, &paints).expect("refine");
1698 assert_eq!(a.viewports.len(), b.viewports.len());
1699 for (va, vb) in a.viewports.iter().zip(b.viewports.iter()) {
1700 assert!(
1701 (va.x - vb.x).abs() < 1e-9 && (va.y - vb.y).abs() < 1e-9,
1702 "mol {} moved: elk ({},{}) refine ({},{})",
1703 va.id.as_deref().unwrap_or("?"),
1704 va.x,
1705 va.y,
1706 vb.x,
1707 vb.y
1708 );
1709 }
1710 }
1711}