Skip to main content

xpict_core/doc/
fit.rs

1//! Post-layout scene fit — AABB of all ink + configurable viewport margin.
2
3use crate::scene::{Primitive, Scene};
4
5/// Default gap (px) between content AABB and SVG viewBox edge (small house pad).
6pub const VIEWPORT_MARGIN_DEFAULT: f64 = 4.0;
7
8/// Resolve a viewport margin: finite ≥ 0, else house default.
9pub fn resolve_viewport_margin(pad: Option<f64>) -> f64 {
10    pad.filter(|p| p.is_finite() && *p >= 0.0)
11        .unwrap_or(VIEWPORT_MARGIN_DEFAULT)
12}
13
14/// Recompute the SVG viewBox from painted ink after layout.
15///
16/// AABB over viewport layers (document space), overlays, and halo. The camera
17/// is `viewBox = (min - margin) + content size + 2·margin`. Geometry is not
18/// translated; path `d` is not rewritten.
19pub fn fit_scene(mut scene: Scene, margin: f64) -> Scene {
20    let margin = if margin.is_finite() && margin >= 0.0 {
21        margin
22    } else {
23        VIEWPORT_MARGIN_DEFAULT
24    };
25
26    let Some((min_x, min_y, max_x, max_y)) = content_aabb(&scene) else {
27        // Nothing to measure — leave declared canvas alone.
28        return scene;
29    };
30
31    scene.x = min_x - margin;
32    scene.y = min_y - margin;
33    let content_w = (max_x - min_x).max(0.0);
34    let content_h = (max_y - min_y).max(0.0);
35    scene.width = content_w + 2.0 * margin;
36    scene.height = content_h + 2.0 * margin;
37
38    // Keep the primary viewport frame aligned with the fitted canvas (layout
39    // and lone-mol SVG both read these).
40    if scene.viewports.len() == 1 {
41        if let Some(vp) = scene.viewports.first_mut() {
42            vp.width = scene.width;
43            vp.height = scene.height;
44        }
45    }
46
47    scene
48}
49
50fn content_aabb(scene: &Scene) -> Option<(f64, f64, f64, f64)> {
51    let mut min_x = f64::INFINITY;
52    let mut min_y = f64::INFINITY;
53    let mut max_x = f64::NEG_INFINITY;
54    let mut max_y = f64::NEG_INFINITY;
55    let mut any = false;
56
57    for vp in &scene.viewports {
58        let mut layer_ink = false;
59        let (ox, oy) = vp.local_origin();
60        for layer in &vp.layers {
61            for p in &layer.primitives {
62                expand_prim(p, ox, oy, &mut min_x, &mut min_y, &mut max_x, &mut max_y);
63                layer_ink = true;
64                any = true;
65            }
66        }
67        // Empty placeholder viewports (compose tests): use the layout frame.
68        // Real mols measure ink only so house PAD_PX can shrink away.
69        if !layer_ink && (vp.width > 0.0 || vp.height > 0.0) {
70            min_x = min_x.min(vp.x);
71            min_y = min_y.min(vp.y);
72            max_x = max_x.max(vp.x + vp.width);
73            max_y = max_y.max(vp.y + vp.height);
74            any = true;
75        }
76    }
77    for p in scene.halo.iter().chain(scene.overlays.iter()) {
78        expand_prim(p, 0.0, 0.0, &mut min_x, &mut min_y, &mut max_x, &mut max_y);
79        any = true;
80    }
81
82    if !any || !min_x.is_finite() {
83        return None;
84    }
85    Some((min_x, min_y, max_x, max_y))
86}
87
88fn expand_prim(
89    p: &Primitive,
90    ox: f64,
91    oy: f64,
92    min_x: &mut f64,
93    min_y: &mut f64,
94    max_x: &mut f64,
95    max_y: &mut f64,
96) {
97    match p {
98        Primitive::Circle {
99            cx,
100            cy,
101            r,
102            stroke_width,
103            ..
104        } => {
105            let grow = r + stroke_width.max(0.0) * 0.5;
106            *min_x = min_x.min(ox + cx - grow);
107            *min_y = min_y.min(oy + cy - grow);
108            *max_x = max_x.max(ox + cx + grow);
109            *max_y = max_y.max(oy + cy + grow);
110        }
111        Primitive::Text {
112            x, y, font_size, ..
113        } => {
114            // Conservative ink box around baseline.
115            let em = font_size.max(1.0);
116            *min_x = min_x.min(ox + x - em);
117            *min_y = min_y.min(oy + y - em);
118            *max_x = max_x.max(ox + x + em * 2.0);
119            *max_y = max_y.max(oy + y + em * 0.4);
120        }
121        Primitive::Path {
122            d, stroke_width, ..
123        } => {
124            let grow = stroke_width.max(0.0) * 0.5;
125            for (x, y) in path_coords(d) {
126                *min_x = min_x.min(ox + x - grow);
127                *min_y = min_y.min(oy + y - grow);
128                *max_x = max_x.max(ox + x + grow);
129                *max_y = max_y.max(oy + y + grow);
130            }
131        }
132    }
133}
134
135fn path_coords(d: &str) -> Vec<(f64, f64)> {
136    let mut nums = Vec::new();
137    let mut cur = String::new();
138    for c in d.chars() {
139        if c.is_ascii_digit() || c == '.' || c == '-' || c == '+' || c == 'e' || c == 'E' {
140            cur.push(c);
141        } else if !cur.is_empty() {
142            if let Ok(v) = cur.parse::<f64>() {
143                nums.push(v);
144            }
145            cur.clear();
146        }
147    }
148    if !cur.is_empty() {
149        if let Ok(v) = cur.parse::<f64>() {
150            nums.push(v);
151        }
152    }
153    let mut out = Vec::new();
154    let mut i = 0;
155    while i + 1 < nums.len() {
156        out.push((nums[i], nums[i + 1]));
157        i += 2;
158    }
159    out
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165    use crate::scene::{Layer, LayerName, Viewport};
166
167    fn path_scene(d: &str) -> Scene {
168        // Oversized declared canvas; viewport frame left empty so fit uses ink only.
169        Scene {
170            width: 200.0,
171            height: 200.0,
172            viewports: vec![Viewport {
173                id: Some("m".into()),
174                x: 0.0,
175                y: 0.0,
176                ox: 0.0,
177                oy: 0.0,
178                width: 0.0,
179                height: 0.0,
180                layers: vec![Layer {
181                    name: LayerName::Bonds,
182                    primitives: vec![Primitive::Path {
183                        d: d.into(),
184                        stroke: Some("#000".into()),
185                        fill: Some("none".into()),
186                        stroke_width: 1.0,
187                        opacity: 1.0,
188                        stroke_dasharray: None,
189                        stroke_linecap: None,
190                        class: None,
191                        data_text: None,
192                    }],
193                }],
194            }],
195            overlays: vec![],
196            halo: vec![],
197            x: 0.0,
198            y: 0.0,
199        }
200    }
201
202    #[test]
203    fn fit_tightens_canvas_to_ink_plus_margin() {
204        let scene = path_scene("M 10 10 L 30 10 L 30 40");
205        let margin = 4.0;
206        let out = fit_scene(scene, margin);
207        assert!(
208            (out.x - (10.0 - 0.5 - margin)).abs() < 1.5,
209            "viewBox min-x should be ink min minus pad: x={}",
210            out.x
211        );
212        // Ink AABB ≈ (10,10)-(30,40) plus half stroke.
213        assert!(
214            (out.width - (20.0 + 1.0 + 2.0 * margin)).abs() < 1.5,
215            "width={}",
216            out.width
217        );
218        assert!(
219            (out.height - (30.0 + 1.0 + 2.0 * margin)).abs() < 1.5,
220            "height={}",
221            out.height
222        );
223        assert!(out.width < 100.0, "should shrink from 200");
224    }
225
226    #[test]
227    fn fit_includes_overlay_caption() {
228        let mut scene = path_scene("M 0 0 L 20 0 L 20 20");
229        scene.overlays.push(Primitive::Path {
230            d: "M 5 50 L 15 50".into(),
231            stroke: Some("none".into()),
232            fill: Some("#111".into()),
233            stroke_width: 0.0,
234            opacity: 1.0,
235            stroke_dasharray: None,
236            stroke_linecap: None,
237            class: Some("mol-caption".into()),
238            data_text: Some("cap".into()),
239        });
240        let out = fit_scene(scene, 4.0);
241        assert!(
242            out.height > 50.0,
243            "fitted height should include caption at y=50: {}",
244            out.height
245        );
246    }
247
248    #[test]
249    fn resolve_margin_default_and_override() {
250        assert!((resolve_viewport_margin(None) - VIEWPORT_MARGIN_DEFAULT).abs() < 1e-12);
251        assert!((resolve_viewport_margin(Some(8.0)) - 8.0).abs() < 1e-12);
252        assert!((resolve_viewport_margin(Some(-1.0)) - VIEWPORT_MARGIN_DEFAULT).abs() < 1e-12);
253    }
254
255    fn last_xy(d: &str) -> (f64, f64) {
256        let nums: Vec<f64> = d
257            .split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-'))
258            .filter_map(|s| s.parse().ok())
259            .collect();
260        (nums[nums.len() - 2], nums[nums.len() - 1])
261    }
262
263    #[test]
264    fn fit_keeps_catmull_head_on_the_shaft() {
265        use crate::arrows::{edge_primitives, EdgePaintIn};
266        use crate::doc::EdgeArrow;
267        let edge = EdgePaintIn {
268            pts: vec![(20.0, 10.0), (80.0, 40.0), (90.0, 140.0)],
269            arrow: EdgeArrow::Forward,
270            routing: None,
271            color: Some("#0072b2".into()),
272            stroke_width: Some(4.8),
273            dashed: false,
274            label: None,
275            label_pos: None,
276            index: 0,
277            curve_catmull: true,
278            label_xy: None,
279            label_rotate: None,
280        };
281        let prims = edge_primitives(&edge);
282        let overlays: Vec<Primitive> = prims
283            .into_iter()
284            .filter_map(|p| match p {
285                crate::arrows::EdgePrim::Path {
286                    d,
287                    stroke,
288                    fill,
289                    stroke_width,
290                    class,
291                    ..
292                } => Some(Primitive::Path {
293                    d,
294                    stroke: Some(stroke),
295                    fill: Some(fill),
296                    stroke_width,
297                    opacity: 1.0,
298                    stroke_dasharray: None,
299                    stroke_linecap: None,
300                    class: Some(class),
301                    data_text: None,
302                }),
303                _ => None,
304            })
305            .collect();
306        let before: Vec<String> = overlays
307            .iter()
308            .filter_map(|p| match p {
309                Primitive::Path { d, .. } => Some(d.clone()),
310                _ => None,
311            })
312            .collect();
313        let scene = Scene {
314            width: 400.0,
315            height: 400.0,
316            x: 0.0,
317            y: 0.0,
318            viewports: vec![],
319            overlays,
320            halo: vec![],
321        };
322        let out = fit_scene(scene, 4.0);
323        let after: Vec<String> = out
324            .overlays
325            .iter()
326            .filter_map(|p| match p {
327                Primitive::Path { d, .. } => Some(d.clone()),
328                _ => None,
329            })
330            .collect();
331        assert_eq!(
332            after, before,
333            "fit crops with viewBox; it must not rewrite d"
334        );
335        assert!(
336            out.x.abs() > 1.0 || out.y.abs() > 1.0,
337            "viewBox origin should track ink, not stay at 0: ({}, {})",
338            out.x,
339            out.y
340        );
341        let shaft = after.iter().find(|d| d.contains('C')).expect("cubic shaft");
342        let head = after
343            .iter()
344            .find(|d| d.contains('Z') || d.contains('z'))
345            .expect("head");
346        let (sx, sy) = last_xy(shaft);
347        let hnums: Vec<f64> = head
348            .split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-'))
349            .filter_map(|s| s.parse().ok())
350            .collect();
351        let (bx, by) = ((hnums[0] + hnums[4]) * 0.5, (hnums[1] + hnums[5]) * 0.5);
352        let gap = (sx - bx).hypot(sy - by);
353        assert!(
354            gap < 0.6,
355            "head stays on the shaft because neither d moved; gap={gap}"
356        );
357    }
358}