d2-rs-math 0.1.12

Rust port of D2's d2latex package and mathjax-go: LaTeX layout and SVG.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// SPDX-License-Identifier: MPL-2.0
//! Upstream 8558856dc d2svgimport/effects.go: SVG effect regions and masks.
use super::{
    svg_compile::Compilation,
    svg_gradient_tree::Element,
    svg_scene::{Clip, Mask, Scene, Work},
    svg_style::Style,
    svg_xml_document::Document,
};
const IDENTITY: [f64; 6] = [1., 0., 0., 1., 0., 0.];
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Region {
    pub units: u8,
    pub content_units: u8,
    pub values: [f64; 4],
    pub percentages: [bool; 4],
}
fn units(raw: &str, fallback: u8) -> Result<u8, String> {
    match raw.trim() {
        "" => Ok(fallback),
        "objectBoundingBox" => Ok(0),
        "userSpaceOnUse" => Ok(1),
        _ => Err("expected objectBoundingBox or userSpaceOnUse".into()),
    }
}
impl Region {
    pub fn compile(
        source: &str,
        el: &Element,
        units_name: &str,
        content_name: &str,
    ) -> Result<Self, String> {
        let property = |key: &str, reason: String| {
            format!(
                "d2svgimport: {source}: element <{}> has invalid {key}: {reason}",
                el.name
            )
        };
        let mut out = Self {
            units: units(
                el.attrs.get(units_name).map(String::as_str).unwrap_or(""),
                0,
            )
            .map_err(|e| property(units_name, e))?,
            content_units: units(
                el.attrs.get(content_name).map(String::as_str).unwrap_or(""),
                1,
            )
            .map_err(|e| property(content_name, e))?,
            values: [-0.1, -0.1, 1.2, 1.2],
            percentages: [true; 4],
        };
        for (n, key) in ["x", "y", "width", "height"].iter().enumerate() {
            if let Some(raw) = el.attrs.get(*key) {
                let raw = raw.trim();
                let (number, percent) = raw.strip_suffix('%').map_or((raw, false), |n| (n, true));
                if percent && number.trim() != number {
                    return Err(property(
                        key,
                        "percentage sign must follow its number".into(),
                    ));
                }
                let value = super::svg_length::length(number, !percent && out.units == 1)
                    .map_err(|e| property(key, e))?;
                out.values[n] = if percent { value / 100. } else { value };
                out.percentages[n] = percent;
            }
        }
        if out.values[2] < 0. || out.values[3] < 0. {
            return Err(format!(
                "d2svgimport: {source}: element <{}> has negative region dimensions",
                el.name
            ));
        }
        Ok(out)
    }
    pub fn bounds(&self, object: [f64; 4], viewport: [f64; 4]) -> [f64; 4] {
        let mut out = self.values;
        for n in 0..4 {
            if self.units == 0 {
                out[n] *= object[2 + n % 2];
                if n < 2 {
                    out[n] += object[n];
                }
            } else if self.percentages[n] {
                out[n] *= viewport[2 + n % 2];
            }
        }
        out
    }
}
pub fn compile_mask(source: &str, el: &Element) -> Result<Region, String> {
    if !matches!(
        el.attrs.get("mask-type").map(|s| s.trim()).unwrap_or(""),
        "" | "luminance" | "alpha"
    ) {
        return Err(format!(
            "d2svgimport: {source}: element <mask> has unsupported mask-type"
        ));
    }
    Region::compile(source, el, "maskUnits", "maskContentUnits")
}
fn context(cancel: Option<&d2_rs_core::CancellationToken>) -> Result<(), String> {
    match cancel.and_then(d2_rs_core::CancellationToken::error) {
        Some(d2_rs_core::LayoutError::DeadlineExceeded) => Err("context deadline exceeded".into()),
        Some(_) => Err("context canceled".into()),
        None => Ok(()),
    }
}
pub fn object_bounds(
    source: &str,
    scene: &Scene,
    root: usize,
    cancel: Option<&d2_rs_core::CancellationToken>,
) -> Result<[f64; 4], String> {
    let mut bounds = super::svg_bounds::Bounds::default();
    let mut stack = vec![(root, IDENTITY)];
    while let Some((index, transform)) = stack.pop() {
        context(cancel)?;
        let node = &scene.nodes[index];
        if let Some(p) = &node.primitive {
            let mut p = p.clone();
            if matches!(p.geometry.kind, 1..=3) {
                p.fill = Some(super::svg_primitive::Paint::Solid { color: [0; 4] });
                p.stroke = None;
            }
            let b = super::svg_bounds::primitive(&p, transform)
                .map_err(|_| format!("d2svgimport: {source}: invalid effect geometry bounds"))?;
            if !b.finite() {
                return Err(format!(
                    "d2svgimport: {source}: invalid effect geometry bounds"
                ));
            }
            bounds.union(b);
        }
        for &child in &node.children {
            stack.push((
                child,
                super::svg_transform::mul(transform, scene.nodes[child].transform),
            ));
        }
    }
    Ok(if bounds.valid {
        [
            bounds.min[0],
            bounds.min[1],
            bounds.max[0] - bounds.min[0],
            bounds.max[1] - bounds.min[1],
        ]
    } else {
        [0.; 4]
    })
}
pub fn region_clip(source: &str, region: [f64; 4], work: &mut Work) -> Result<Clip, String> {
    if 5 > work
        .budget
        .max_commands
        .saturating_sub(work.budget.commands)
    {
        return Err(format!(
            "d2svgimport: {source}: emitted path command count exceeds limit {}",
            work.budget.max_commands
        ));
    }
    work.budget.commands += 5;
    let [x, y, w, h] = region;
    let point = |kind, xy| super::svg_path::Command {
        kind,
        points: [xy, [0.; 2], [0.; 2]],
        ..Default::default()
    };
    Ok(Clip {
        commands: vec![
            point(0, [0., 0.]),
            point(1, [w, 0.]),
            point(1, [w, h]),
            point(1, [0., h]),
            point(5, [0., 0.]),
        ],
        fill_rule: 0,
        transform: [1., 0., 0., 1., x, y],
    })
}
pub fn apply(
    source: &str,
    document: &Document,
    compiled: &Compilation,
    scene: &mut Scene,
    index: usize,
    style: &Style,
    root_color: [u8; 4],
    building_mask: bool,
    work: &mut Work,
    cancel: Option<&d2_rs_core::CancellationToken>,
) -> Result<(usize, bool), String> {
    let mut index = index;
    if !style.filter.is_empty() {
        let resource = document.ids[&style.filter];
        let spec = compiled.states[resource]
            .filter_region
            .as_ref()
            .expect("compiled filter region");
        let bounds = object_bounds(source, scene, index, cancel)?;
        let region = spec.bounds(bounds, style.viewport);
        if region[2] <= 0. || region[3] <= 0. {
            scene.nodes[index].opacity = 0.;
            return Ok((index, false));
        }
        let mut blur = compiled.states[resource].blur;
        if spec.content_units == 0 {
            blur.sigma_x *= bounds[2];
            blur.sigma_y *= bounds[3];
        }
        let wrapper = super::svg_scene::node(scene, work, source, None, 0)?;
        scene.nodes[wrapper].clip = Some(region_clip(source, region, work)?);
        scene.nodes[wrapper].opacity = scene.nodes[index].opacity;
        scene.nodes[index].opacity = 1.;
        scene.nodes[wrapper].id = std::mem::take(&mut scene.nodes[index].id);
        scene.nodes[wrapper].transform = scene.nodes[index].transform;
        scene.nodes[index].transform = IDENTITY;
        scene.nodes[index].filters = vec![blur];
        scene.nodes[wrapper].children.push(index);
        index = wrapper;
    }
    if style.mask.is_empty() {
        return Ok((index, true));
    }
    if building_mask {
        return Err(format!(
            "d2svgimport: {source}: nested mask references are unsupported"
        ));
    }
    let mask = document.ids[&style.mask];
    let spec = compiled.states[mask]
        .mask_region
        .as_ref()
        .expect("compiled mask region");
    let object = object_bounds(source, scene, index, cancel)?;
    let region = spec.bounds(object, style.viewport);
    if region[2] <= 0. || region[3] <= 0. {
        scene.nodes[index].opacity = 0.;
        return Ok((index, false));
    }
    let resources = document
        .ids
        .iter()
        .map(|(id, &i)| {
            (
                id.clone(),
                super::svg_resources::Resource {
                    name: compiled
                        .elements
                        .get(i)
                        .map(|e| e.name.clone())
                        .unwrap_or_default(),
                    gradient: compiled.elements.get(i).and_then(|e| e.gradient.clone()),
                },
            )
        })
        .collect();
    let mut inherited = Style::default();
    inherited.paint.color = root_color;
    inherited.viewport = style.viewport;
    let mut ancestors = vec![];
    let mut parent = document.elements[mask].parent;
    while let Some(i) = parent {
        ancestors.push(i);
        parent = document.elements[i].parent;
    }
    for &i in ancestors.iter().rev() {
        inherited = super::svg_style::compute(
            source,
            &compiled.elements[i].name,
            &inherited,
            &compiled.elements[i].declarations,
            &resources,
            cancel,
        )?;
    }
    inherited.viewport = if spec.content_units == 0 {
        [0., 0., 1., 1.]
    } else {
        style.viewport
    };
    let old_root = scene.root;
    super::svg_scene::instantiate_effects(
        source,
        document,
        compiled,
        mask,
        inherited,
        String::new(),
        0,
        true,
        scene,
        work,
        cancel,
        true,
    )?;
    let content = scene.root;
    scene.root = old_root;
    let Some(content) = content else {
        scene.nodes[index].opacity = 0.;
        return Ok((index, false));
    };
    if spec.content_units == 0 {
        scene.nodes[content].transform = super::svg_transform::mul(
            [object[2], 0., 0., object[3], object[0], object[1]],
            scene.nodes[content].transform,
        );
    }
    let wrapper = super::svg_scene::node(scene, work, source, None, 0)?;
    scene.nodes[wrapper].children.push(content);
    scene.nodes[wrapper].clip = Some(region_clip(source, region, work)?);
    let kind = if compiled.elements[mask]
        .attrs
        .get("mask-type")
        .is_some_and(|v| v.trim() == "alpha")
    {
        0
    } else {
        1
    };
    scene.nodes[index].mask = Some(Mask {
        kind,
        root: wrapper,
    });
    Ok((index, true))
}

#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Blur {
    pub sigma_x: f64,
    pub sigma_y: f64,
    pub linear_rgb: bool,
}
pub fn compile_filter(
    source: &str,
    document: &Document,
    elements: &[Element],
    states: &mut [super::svg_element::State],
    index: usize,
    cancel: Option<&d2_rs_core::CancellationToken>,
) -> Result<(), String> {
    let el = &elements[index];
    let parent = document.elements[index]
        .parent
        .map(|i| elements[i].name.as_str());
    let error = |reason: &str| format!("d2svgimport: {source}: {reason}");
    if el.name == "feGaussianBlur" {
        if parent != Some("filter") || !el.children.is_empty() {
            return Err(error("<feGaussianBlur> must be a leaf inside a filter"));
        }
        return Ok(());
    }
    if !matches!(parent, Some("svg" | "g" | "defs")) {
        return Err(error(
            "element <filter> must be inside <svg>, <g> or <defs>",
        ));
    }
    if el.children.len() != 1 || elements[el.children[0]].name != "feGaussianBlur" {
        return Err(error(
            "element <filter> supports one feGaussianBlur of SourceGraphic",
        ));
    }
    let primitive = &elements[el.children[0]];
    if primitive
        .attrs
        .get("in")
        .is_some_and(|v| v != "SourceGraphic")
    {
        return Err(error(
            "element <feGaussianBlur> supports only SourceGraphic",
        ));
    }
    let mut blur = Blur {
        linear_rgb: true,
        ..Default::default()
    };
    for resource in [el, primitive] {
        if let Some(value) = resource.attrs.get("color-interpolation-filters") {
            match value.as_str() {
                "linearRGB" => blur.linear_rgb = true,
                "sRGB" => blur.linear_rgb = false,
                "inherit" => {}
                _ => {
                    return Err(error(&format!(
                        "unsupported color-interpolation-filters on <{}>",
                        resource.name
                    )));
                }
            }
        }
    }
    if let Some(raw) = primitive.attrs.get("stdDeviation") {
        let values = super::svg_geometry::list(raw, 2, cancel)
            .map_err(|_| error("feGaussianBlur requires one or two deviations"))?;
        if values.is_empty() {
            return Err(error("feGaussianBlur requires one or two deviations"));
        }
        for (n, value) in values.iter().enumerate() {
            let sigma = super::svg_length::number(value)
                .map_err(|_| error("feGaussianBlur requires nonnegative finite deviations"))?;
            if sigma < 0. {
                return Err(error(
                    "feGaussianBlur requires nonnegative finite deviations",
                ));
            }
            if n == 0 {
                blur.sigma_x = sigma;
            }
            blur.sigma_y = sigma;
        }
    }
    states[index].blur = blur;
    states[index].filter_region = Some(Region::compile(
        source,
        el,
        "filterUnits",
        "primitiveUnits",
    )?);
    Ok(())
}