icu_lib 0.7.0

Image Converter Ultra Library
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
use mirx::{
    Color, FillRule, Fixed, GradientStop, GradientUnits, LineCap, LineJoin, LinearGradient,
    Paint as MirxPaint, Path as MirxPath, PathCmd, Point, RadialGradient, ResourceRef, Scene,
    SceneOp, SpreadMode, Transform,
};
use std::borrow::Cow;
use usvg::tiny_skia_path::Path as SkPath;

fn fixed_from_f32(v: f32) -> Fixed {
    Fixed::from_raw((v * 256.0).round() as i32)
}

fn color_from_usvg(c: usvg::Color) -> Color {
    Color {
        r: c.red,
        g: c.green,
        b: c.blue,
        a: 255,
    }
}

fn transform_from_usvg(t: usvg::Transform) -> Transform {
    Transform {
        m00: fixed_from_f32(t.sx as f32),
        m01: fixed_from_f32(t.kx as f32),
        tx: fixed_from_f32(t.tx as f32),
        m10: fixed_from_f32(t.ky as f32),
        m11: fixed_from_f32(t.sy as f32),
        ty: fixed_from_f32(t.ty as f32),
    }
}

fn convert_path(path: &SkPath) -> MirxPath {
    let mut cmds: Vec<PathCmd> = Vec::new();
    for seg in path.segments() {
        match seg {
            usvg::tiny_skia_path::PathSegment::MoveTo(p) => {
                cmds.push(PathCmd::MoveTo(Point::new(
                    fixed_from_f32(p.x as f32),
                    fixed_from_f32(p.y as f32),
                )));
            }
            usvg::tiny_skia_path::PathSegment::LineTo(p) => {
                cmds.push(PathCmd::LineTo(Point::new(
                    fixed_from_f32(p.x as f32),
                    fixed_from_f32(p.y as f32),
                )));
            }
            usvg::tiny_skia_path::PathSegment::QuadTo(p1, p2) => {
                cmds.push(PathCmd::QuadTo {
                    ctrl: Point::new(fixed_from_f32(p1.x as f32), fixed_from_f32(p1.y as f32)),
                    end: Point::new(fixed_from_f32(p2.x as f32), fixed_from_f32(p2.y as f32)),
                });
            }
            usvg::tiny_skia_path::PathSegment::CubicTo(p1, p2, p3) => {
                cmds.push(PathCmd::CubicTo {
                    ctrl1: Point::new(fixed_from_f32(p1.x as f32), fixed_from_f32(p1.y as f32)),
                    ctrl2: Point::new(fixed_from_f32(p2.x as f32), fixed_from_f32(p2.y as f32)),
                    end: Point::new(fixed_from_f32(p3.x as f32), fixed_from_f32(p3.y as f32)),
                });
            }
            usvg::tiny_skia_path::PathSegment::Close => {
                cmds.push(PathCmd::Close);
            }
        }
    }
    MirxPath { cmds }
}

fn line_cap_from_usvg(c: usvg::LineCap) -> LineCap {
    match c {
        usvg::LineCap::Butt => LineCap::Butt,
        usvg::LineCap::Round => LineCap::Round,
        usvg::LineCap::Square => LineCap::Square,
    }
}

fn line_join_from_usvg(j: usvg::LineJoin) -> LineJoin {
    match j {
        usvg::LineJoin::Miter | usvg::LineJoin::MiterClip => LineJoin::Miter,
        usvg::LineJoin::Round => LineJoin::Round,
        usvg::LineJoin::Bevel => LineJoin::Bevel,
    }
}

fn paint_to_mirx(paint: &usvg::Paint, opacity: u8) -> Option<MirxPaint> {
    match paint {
        usvg::Paint::Color(c) => {
            let mut color = color_from_usvg(*c);
            color.a = ((color.a as u32 * opacity as u32) / 255).min(255) as u8;
            Some(MirxPaint::Color(color))
        }
        usvg::Paint::LinearGradient(g) => {
            let stops = gradient_stops_from_usvg(g.stops());
            Some(MirxPaint::LinearGradient(LinearGradient {
                start: point_from_usvg(g.x1(), g.y1()),
                end: point_from_usvg(g.x2(), g.y2()),
                stops: Cow::Owned(stops),
                spread: spread_from_usvg(g.spread_method()),
                units: GradientUnits::ObjectBoundingBox,
                transform: transform_from_usvg(g.transform()),
            }))
        }
        usvg::Paint::RadialGradient(g) => {
            let stops = gradient_stops_from_usvg(g.stops());
            Some(MirxPaint::RadialGradient(RadialGradient {
                center: point_from_usvg(g.cx(), g.cy()),
                radius: fixed_from_f32(g.r().get() as f32),
                focal: point_from_usvg(g.fx(), g.fy()),
                focal_radius: Fixed::ZERO,
                stops: Cow::Owned(stops),
                spread: spread_from_usvg(g.spread_method()),
                units: GradientUnits::ObjectBoundingBox,
                transform: transform_from_usvg(g.transform()),
            }))
        }
        usvg::Paint::Pattern(_) => None,
    }
}

fn point_from_usvg(x: f32, y: f32) -> Point {
    Point::new(fixed_from_f32(x), fixed_from_f32(y))
}

fn gradient_stops_from_usvg(stops: &[usvg::Stop]) -> Vec<GradientStop> {
    stops
        .iter()
        .map(|s| GradientStop {
            offset: fixed_from_f32(s.offset().get() as f32),
            color: color_from_usvg(s.color()),
        })
        .collect()
}

fn spread_from_usvg(s: usvg::SpreadMethod) -> SpreadMode {
    match s {
        usvg::SpreadMethod::Pad => SpreadMode::Pad,
        usvg::SpreadMethod::Reflect => SpreadMode::Reflect,
        usvg::SpreadMethod::Repeat => SpreadMode::Repeat,
    }
}

fn filter_token(filters: &[std::sync::Arc<usvg::filter::Filter>]) -> String {
    let mut parts = Vec::new();
    for f in filters {
        for prim in f.primitives() {
            match prim.kind() {
                usvg::filter::Kind::GaussianBlur(gb) => {
                    parts.push(format!(
                        "blur:{}:{}",
                        gb.std_dev_x().get(),
                        gb.std_dev_y().get()
                    ));
                }
                usvg::filter::Kind::ColorMatrix(cm) => {
                    let kind = match cm.kind() {
                        usvg::filter::ColorMatrixKind::Matrix(_) => "matrix",
                        usvg::filter::ColorMatrixKind::Saturate(_) => "saturate",
                        usvg::filter::ColorMatrixKind::HueRotate(_) => "hueRotate",
                        usvg::filter::ColorMatrixKind::LuminanceToAlpha => "luminance",
                    };
                    parts.push(format!("cm:{}", kind));
                }
                _ => {}
            }
        }
    }
    parts.join(";")
}

fn walk_group(group: &usvg::Group, ops: &mut Vec<SceneOp>) {
    let group_opacity = group.opacity().get();
    let filters = group.filters();
    let has_filter = !filters.is_empty();
    let push_group = (group_opacity < 1.0 && group_opacity > 0.0) || has_filter;
    let filter_ref = if has_filter {
        Some(ResourceRef::Token(filter_token(filters)))
    } else {
        None
    };
    if push_group {
        ops.push(SceneOp::GroupBegin {
            transform: None,
            opacity: if group_opacity < 1.0 && group_opacity > 0.0 {
                Some(group.opacity().to_u8())
            } else {
                None
            },
            clip: None,
            mask: None,
            filter: filter_ref,
            disjoint_hint: false,
        });
    }

    let clip_paths: Vec<Vec<SceneOp>> = group
        .clip_path()
        .map(|cp| collect_clip_ops(cp))
        .into_iter()
        .collect();
    for clip_ops in &clip_paths {
        ops.extend_from_slice(clip_ops);
    }

    for node in group.children() {
        match node {
            usvg::Node::Group(g) => walk_group(g, ops),
            usvg::Node::Path(p) => emit_path(p, ops),
            usvg::Node::Image(img) => {
                emit_image(img, ops);
            }
            usvg::Node::Text(t) => walk_group(t.flattened(), ops),
        }
    }

    for _ in &clip_paths {
        ops.push(SceneOp::PopClip);
    }

    if push_group {
        ops.push(SceneOp::GroupEnd);
    }
}

fn emit_image(img: &usvg::Image, ops: &mut Vec<SceneOp>) {
    let kind = img.kind();
    let raw_data: Option<Vec<u8>> = match kind {
        usvg::ImageKind::PNG(data)
        | usvg::ImageKind::JPEG(data)
        | usvg::ImageKind::GIF(data)
        | usvg::ImageKind::WEBP(data) => Some(data.to_vec()),
        _ => None,
    };
    let raw_data = match raw_data {
        Some(d) => d,
        None => return,
    };

    let rgba = match image::load_from_memory(&raw_data) {
        Ok(dyn_img) => dyn_img.to_rgba8(),
        Err(_) => return,
    };
    let (w, h) = rgba.dimensions();
    if w == 0 || h == 0 {
        return;
    }

    let mut r_sum: u64 = 0;
    let mut g_sum: u64 = 0;
    let mut b_sum: u64 = 0;
    let count = (w as u64) * (h as u64);
    for px in rgba.pixels() {
        r_sum += px.0[0] as u64;
        g_sum += px.0[1] as u64;
        b_sum += px.0[2] as u64;
    }
    let avg = mirx::Color {
        r: (r_sum / count).min(255) as u8,
        g: (g_sum / count).min(255) as u8,
        b: (b_sum / count).min(255) as u8,
        a: 255,
    };

    let abs_tf = img.abs_transform();
    let size = img.size();
    let transform = if abs_tf.is_identity() {
        Transform::IDENTITY
    } else {
        transform_from_usvg(abs_tf)
    };

    let area = mirx::Rect::new(
        Fixed::ZERO,
        Fixed::ZERO,
        fixed_from_f32(size.width() as f32),
        fixed_from_f32(size.height() as f32),
    );

    ops.push(SceneOp::FillRect {
        area,
        transform,
        quad: None,
        color: avg,
        radius: Fixed::ZERO,
        opa: 255,
    });
}

fn collect_clip_ops(clip: &usvg::ClipPath) -> Vec<SceneOp> {
    let mut ops = Vec::new();
    for node in clip.root().children() {
        if let usvg::Node::Path(p) = node {
            let path = convert_path(p.data());
            if path.cmds.is_empty() {
                continue;
            }
            let abs_tf = p.abs_transform();
            let transform = if abs_tf.is_identity() {
                Transform::IDENTITY
            } else {
                transform_from_usvg(abs_tf)
            };
            let fill_rule = match p.fill().map(|f| f.rule()) {
                Some(usvg::FillRule::EvenOdd) => FillRule::EvenOdd,
                _ => FillRule::NonZero,
            };
            ops.push(SceneOp::PushClip {
                path,
                transform,
                fill_rule,
            });
        }
    }
    ops
}

fn emit_path(p: &usvg::Path, ops: &mut Vec<SceneOp>) {
    let abs_tf = p.abs_transform();
    let path = convert_path(p.data());
    if path.cmds.is_empty() {
        return;
    }
    let transform = if abs_tf.is_identity() {
        Transform::IDENTITY
    } else {
        transform_from_usvg(abs_tf)
    };
    if let Some(fill) = p.fill() {
        if let Some(paint) = paint_to_mirx(fill.paint(), fill.opacity().to_u8()) {
            let fill_rule = match fill.rule() {
                usvg::FillRule::NonZero => FillRule::NonZero,
                usvg::FillRule::EvenOdd => FillRule::EvenOdd,
            };
            let opa = fill.opacity().to_u8();
            ops.push(SceneOp::FillPath {
                path: path.clone(),
                transform,
                paint,
                opa,
                fill_rule,
            });
        }
    }
    if let Some(stroke) = p.stroke() {
        if let Some(paint) = paint_to_mirx(stroke.paint(), stroke.opacity().to_u8()) {
            let width = fixed_from_f32(stroke.width().get() as f32);
            if width > Fixed::ZERO {
                ops.push(SceneOp::StrokePath {
                    path,
                    transform,
                    paint,
                    width,
                    opa: stroke.opacity().to_u8(),
                    line_cap: line_cap_from_usvg(stroke.linecap()),
                    line_join: line_join_from_usvg(stroke.linejoin()),
                    miter_limit: fixed_from_f32(stroke.miterlimit().get() as f32),
                    dash: Cow::Owned(
                        stroke
                            .dasharray()
                            .map(|d| d.iter().map(|&v| fixed_from_f32(v)).collect())
                            .unwrap_or_default(),
                    ),
                });
            }
        }
    }
}

pub fn svg_to_scene(data: &[u8]) -> Scene {
    let opt = usvg::Options::default();
    match usvg::Tree::from_data(data, &opt) {
        Ok(tree) => {
            let mut ops: Vec<SceneOp> = Vec::new();
            walk_group(tree.root(), &mut ops);
            Scene { ops }
        }
        Err(_) => Scene { ops: Vec::new() },
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_empty_svg_returns_empty_scene() {
        let svg = b"<?xml version=\"1.0\"?><svg xmlns=\"http://www.w3.org/2000/svg\" width=\"10\" height=\"10\"></svg>";
        let scene = svg_to_scene(svg);
        assert!(scene.ops.is_empty());
    }

    #[test]
    fn parse_path_with_move_line_close() {
        let svg = b"<svg><path d=\"M0 0 L10 10 Z\" fill=\"#FF0000\"/></svg>";
        let scene = svg_to_scene(svg);
        assert_eq!(scene.ops.len(), 1);
        match &scene.ops[0] {
            SceneOp::FillPath { path, paint, .. } => {
                assert_eq!(path.cmds.len(), 3);
                assert!(matches!(paint, MirxPaint::Color(color) if color.r == 255));
            }
            _ => panic!("expected FillPath"),
        }
    }

    #[test]
    fn parse_rect_produces_fill() {
        let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"><rect x=\"5\" y=\"6\" width=\"20\" height=\"30\" fill=\"blue\"/></svg>";
        let scene = svg_to_scene(svg);
        let has_fill = scene.ops.iter().any(|op| match op {
            SceneOp::FillPath {
                paint: MirxPaint::Color(color),
                ..
            }
            | SceneOp::FillRect { color, .. } => color.b == 255,
            _ => false,
        });
        assert!(has_fill, "expected a blue fill from <rect>");
    }

    #[test]
    fn parse_line_produces_stroke() {
        let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"><line x1=\"0\" y1=\"0\" x2=\"10\" y2=\"10\" stroke=\"black\" stroke-width=\"2\"/></svg>";
        let scene = svg_to_scene(svg);
        let has_stroke = scene
            .ops
            .iter()
            .any(|op| matches!(op, SceneOp::StrokePath { .. } | SceneOp::Line { .. }));
        assert!(has_stroke, "expected a stroke from <line>");
    }

    #[test]
    fn parse_stroke_only_path_produces_stroke_op() {
        let svg = b"<svg><path d=\"M0 0 L10 10\" fill=\"none\" stroke=\"#3a4552\" stroke-width=\"5\"/></svg>";
        let scene = svg_to_scene(svg);
        let has_stroke = scene
            .ops
            .iter()
            .any(|op| matches!(op, SceneOp::StrokePath { .. }));
        assert!(has_stroke);
    }

    #[test]
    fn parse_use_resolves_defs_path() {
        let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"><defs><path id=\"p\" d=\"M0 0 L10 0 L10 10 Z\"/></defs><use href=\"#p\" transform=\"translate(5 5)\" fill=\"#FF0000\"/></svg>";
        let scene = svg_to_scene(svg);
        let fill_count = scene
            .ops
            .iter()
            .filter(|op| matches!(op, SceneOp::FillPath { paint: MirxPaint::Color(color), .. } if color.r == 255))
            .count();
        assert!(
            fill_count >= 1,
            "expected at least one red FillPath from <use>"
        );
    }

    #[test]
    fn parse_group_transform_applies_to_children() {
        let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"><g transform=\"translate(10 10)\"><rect x=\"0\" y=\"0\" width=\"5\" height=\"5\" fill=\"red\"/></g></svg>";
        let scene = svg_to_scene(svg);
        assert!(!scene.ops.is_empty());
    }
}