blinc_svg 0.5.0

SVG loading and rendering for Blinc UI framework
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
//! SVG document type and loading

use std::fs;
use std::path::Path as FilePath;

use blinc_core::{Brush, DrawContext, Path, PathCommand, Point, Rect, Stroke};
use usvg::{Options, Tree};

use crate::error::SvgError;
use crate::path::usvg_path_to_blinc;
use crate::style::{fill_to_brush, stroke_to_blinc};

/// A loaded and parsed SVG document
#[derive(Clone)]
pub struct SvgDocument {
    /// The underlying usvg tree
    tree: Tree,
    /// Original viewBox/size of the SVG
    pub width: f32,
    pub height: f32,
}

/// A drawing command extracted from the SVG
#[derive(Clone, Debug)]
pub enum SvgDrawCommand {
    /// Fill a path with a brush
    FillPath { path: Path, brush: Brush },
    /// Stroke a path with a stroke style and brush
    StrokePath {
        path: Path,
        stroke: Stroke,
        brush: Brush,
    },
}

impl SvgDocument {
    /// Load an SVG document from a file
    pub fn from_file(path: impl AsRef<FilePath>) -> Result<Self, SvgError> {
        let data = fs::read(path)?;
        Self::from_data(&data)
    }

    /// Load an SVG document from raw bytes
    pub fn from_data(data: &[u8]) -> Result<Self, SvgError> {
        let options = Options::default();
        let tree = Tree::from_data(data, &options).map_err(|e| SvgError::Parse(e.to_string()))?;

        let size = tree.size();

        Ok(Self {
            tree,
            width: size.width(),
            height: size.height(),
        })
    }

    /// Load an SVG document from a string
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(svg_str: &str) -> Result<Self, SvgError> {
        Self::from_data(svg_str.as_bytes())
    }

    /// Get the original size of the SVG
    pub fn size(&self) -> (f32, f32) {
        (self.width, self.height)
    }

    /// Get the bounding box of the SVG content
    pub fn bounds(&self) -> Rect {
        Rect::new(0.0, 0.0, self.width, self.height)
    }

    /// Extract all drawing commands from the SVG
    pub fn commands(&self) -> Vec<SvgDrawCommand> {
        let mut commands = Vec::new();
        self.extract_commands(self.tree.root(), &mut commands);
        commands
    }

    /// Recursively extract commands from the node tree
    fn extract_commands(&self, group: &usvg::Group, commands: &mut Vec<SvgDrawCommand>) {
        for child in group.children() {
            match child {
                usvg::Node::Group(g) => {
                    // Recurse into groups (transforms are handled per-path via abs_transform)
                    self.extract_commands(g, commands);
                }
                usvg::Node::Path(p) => {
                    // Convert path to Blinc path and apply the absolute transform
                    let blinc_path = usvg_path_to_blinc(p.data());
                    let transformed_path = apply_transform(&blinc_path, &p.abs_transform());

                    // Handle fill
                    if let Some(fill) = p.fill() {
                        if let Some(brush) = fill_to_brush(fill) {
                            commands.push(SvgDrawCommand::FillPath {
                                path: transformed_path.clone(),
                                brush,
                            });
                        }
                    }

                    // Handle stroke
                    if let Some(stroke) = p.stroke() {
                        if let Some((blinc_stroke, brush)) = stroke_to_blinc(stroke) {
                            commands.push(SvgDrawCommand::StrokePath {
                                path: transformed_path,
                                stroke: blinc_stroke,
                                brush,
                            });
                        }
                    }
                }
                usvg::Node::Image(_) => {
                    // TODO: Handle embedded images
                }
                usvg::Node::Text(_) => {
                    // Text is converted to paths by usvg
                }
            }
        }
    }

    /// Render the SVG to a DrawContext at the given position and scale
    pub fn render(&self, ctx: &mut dyn DrawContext, x: f32, y: f32, scale: f32) {
        let commands = self.commands();

        for cmd in commands {
            match cmd {
                SvgDrawCommand::FillPath { path, brush } => {
                    let scaled = scale_and_translate_path(&path, x, y, scale);
                    ctx.fill_path(&scaled, brush);
                }
                SvgDrawCommand::StrokePath {
                    path,
                    stroke,
                    brush,
                } => {
                    let scaled = scale_and_translate_path(&path, x, y, scale);
                    // Scale stroke width proportionally
                    let scaled_stroke = Stroke::new(stroke.width * scale)
                        .with_cap(stroke.cap)
                        .with_join(stroke.join);
                    ctx.stroke_path(&scaled, &scaled_stroke, brush);
                }
            }
        }
    }

    /// Render the SVG to fit within a given rectangle, maintaining aspect ratio
    pub fn render_fit(&self, ctx: &mut dyn DrawContext, bounds: Rect) {
        let scale_x = bounds.width() / self.width;
        let scale_y = bounds.height() / self.height;
        let scale = scale_x.min(scale_y);

        // Center within bounds
        let scaled_width = self.width * scale;
        let scaled_height = self.height * scale;
        let x = bounds.x() + (bounds.width() - scaled_width) / 2.0;
        let y = bounds.y() + (bounds.height() - scaled_height) / 2.0;

        self.render(ctx, x, y, scale);
    }
}

/// Metadata for an SVG sub-element with a non-empty ID.
/// Used for CSS selector targeting of SVG internals.
#[derive(Clone, Debug)]
pub struct SvgSubElement {
    /// The element's `id` attribute
    pub id: String,
    /// SVG tag name ("path", "circle", "rect", "ellipse", "line", "polygon", "polyline")
    pub tag_name: String,
    /// Current fill color [r, g, b, a] if set
    pub fill: Option<[f32; 4]>,
    /// Current stroke color [r, g, b, a] if set
    pub stroke: Option<[f32; 4]>,
    /// Current stroke width if set
    pub stroke_width: Option<f32>,
    /// Current stroke-dasharray if set
    pub dasharray: Option<Vec<f32>>,
    /// Current stroke-dashoffset
    pub dashoffset: f32,
    /// Element opacity (0.0-1.0)
    pub opacity: f32,
}

/// Extract metadata for all sub-elements with IDs from an SVG string.
///
/// Parses the SVG via usvg and walks the tree, returning metadata for each
/// element that has a non-empty `id` attribute. This enables CSS selector
/// targeting of individual SVG elements.
pub fn extract_element_metadata(svg_str: &str) -> Result<Vec<SvgSubElement>, SvgError> {
    let options = Options::default();
    let tree = Tree::from_data(svg_str.as_bytes(), &options)
        .map_err(|e| SvgError::Parse(e.to_string()))?;
    let mut elements = Vec::new();
    extract_from_group(tree.root(), &mut elements);
    Ok(elements)
}

fn extract_from_group(group: &usvg::Group, elements: &mut Vec<SvgSubElement>) {
    for child in group.children() {
        match child {
            usvg::Node::Group(g) => {
                // Groups can have IDs too
                let id = g.id().to_string();
                if !id.is_empty() {
                    elements.push(SvgSubElement {
                        id,
                        tag_name: "g".to_string(),
                        fill: None,
                        stroke: None,
                        stroke_width: None,
                        dasharray: None,
                        dashoffset: 0.0,
                        opacity: g.opacity().get(),
                    });
                }
                extract_from_group(g, elements);
            }
            usvg::Node::Path(p) => {
                let id = p.id().to_string();
                if !id.is_empty() {
                    let fill = p.fill().and_then(|f| {
                        if let usvg::Paint::Color(c) = f.paint() {
                            Some([
                                c.red as f32 / 255.0,
                                c.green as f32 / 255.0,
                                c.blue as f32 / 255.0,
                                f.opacity().get(),
                            ])
                        } else {
                            None
                        }
                    });
                    let (stroke, stroke_width, dasharray, dashoffset) = if let Some(s) = p.stroke()
                    {
                        let sc = if let usvg::Paint::Color(c) = s.paint() {
                            Some([
                                c.red as f32 / 255.0,
                                c.green as f32 / 255.0,
                                c.blue as f32 / 255.0,
                                s.opacity().get(),
                            ])
                        } else {
                            None
                        };
                        let da = s.dasharray().map(|d| d.to_vec());
                        (sc, Some(s.width().get()), da, s.dashoffset())
                    } else {
                        (None, None, None, 0.0)
                    };
                    // usvg flattens circles/rects/ellipses to paths, so tag_name is always "path"
                    // The original tag name is lost after usvg processing
                    elements.push(SvgSubElement {
                        id,
                        tag_name: "path".to_string(),
                        fill,
                        stroke,
                        stroke_width,
                        dasharray,
                        dashoffset,
                        opacity: 1.0, // path-level opacity is folded into fill/stroke opacity by usvg
                    });
                }
            }
            usvg::Node::Image(_) | usvg::Node::Text(_) => {}
        }
    }
}

/// Apply a usvg Transform to a Blinc Path
fn apply_transform(path: &Path, transform: &usvg::Transform) -> Path {
    if transform.is_identity() {
        return path.clone();
    }

    let (sx, ky, kx, sy, tx, ty) = (
        transform.sx,
        transform.ky,
        transform.kx,
        transform.sy,
        transform.tx,
        transform.ty,
    );

    let transform_point =
        |p: Point| -> Point { Point::new(sx * p.x + kx * p.y + tx, ky * p.x + sy * p.y + ty) };

    let new_commands: Vec<PathCommand> = path
        .commands()
        .iter()
        .map(|cmd| match cmd {
            PathCommand::MoveTo(p) => PathCommand::MoveTo(transform_point(*p)),
            PathCommand::LineTo(p) => PathCommand::LineTo(transform_point(*p)),
            PathCommand::QuadTo { control, end } => PathCommand::QuadTo {
                control: transform_point(*control),
                end: transform_point(*end),
            },
            PathCommand::CubicTo {
                control1,
                control2,
                end,
            } => PathCommand::CubicTo {
                control1: transform_point(*control1),
                control2: transform_point(*control2),
                end: transform_point(*end),
            },
            PathCommand::ArcTo {
                radii,
                rotation,
                large_arc,
                sweep,
                end,
            } => PathCommand::ArcTo {
                radii: *radii,
                rotation: *rotation,
                large_arc: *large_arc,
                sweep: *sweep,
                end: transform_point(*end),
            },
            PathCommand::Close => PathCommand::Close,
        })
        .collect();

    Path::from_commands(new_commands)
}

/// Scale and translate a path for rendering
fn scale_and_translate_path(path: &Path, x: f32, y: f32, scale: f32) -> Path {
    if scale == 1.0 && x == 0.0 && y == 0.0 {
        return path.clone();
    }

    let transform_point = |p: Point| -> Point { Point::new(p.x * scale + x, p.y * scale + y) };

    let new_commands: Vec<PathCommand> = path
        .commands()
        .iter()
        .map(|cmd| match cmd {
            PathCommand::MoveTo(p) => PathCommand::MoveTo(transform_point(*p)),
            PathCommand::LineTo(p) => PathCommand::LineTo(transform_point(*p)),
            PathCommand::QuadTo { control, end } => PathCommand::QuadTo {
                control: transform_point(*control),
                end: transform_point(*end),
            },
            PathCommand::CubicTo {
                control1,
                control2,
                end,
            } => PathCommand::CubicTo {
                control1: transform_point(*control1),
                control2: transform_point(*control2),
                end: transform_point(*end),
            },
            PathCommand::ArcTo {
                radii,
                rotation,
                large_arc,
                sweep,
                end,
            } => PathCommand::ArcTo {
                radii: blinc_core::Vec2::new(radii.x * scale, radii.y * scale),
                rotation: *rotation,
                large_arc: *large_arc,
                sweep: *sweep,
                end: transform_point(*end),
            },
            PathCommand::Close => PathCommand::Close,
        })
        .collect();

    Path::from_commands(new_commands)
}

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

    #[test]
    fn test_parse_simple_svg() {
        let svg = r#"
            <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
                <rect x="10" y="10" width="80" height="80" fill="red"/>
            </svg>
        "#;

        let doc = SvgDocument::from_str(svg).unwrap();
        assert_eq!(doc.width, 100.0);
        assert_eq!(doc.height, 100.0);

        let commands = doc.commands();
        assert!(!commands.is_empty());
    }

    #[test]
    fn test_parse_path_svg() {
        let svg = r#"
            <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
                <path d="M10,10 L90,10 L90,90 L10,90 Z" fill="blue" stroke="black" stroke-width="2"/>
            </svg>
        "#;

        let doc = SvgDocument::from_str(svg).unwrap();
        let commands = doc.commands();

        // Should have both fill and stroke commands
        assert!(commands.len() >= 2);
    }

    #[test]
    fn test_parse_circle_svg() {
        let svg = r#"
            <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
                <circle cx="50" cy="50" r="40" fill="green"/>
            </svg>
        "#;

        let doc = SvgDocument::from_str(svg).unwrap();
        let commands = doc.commands();
        assert!(!commands.is_empty());
    }

    #[test]
    fn test_fill_only_no_stroke() {
        // SVG with fill but no stroke - should NOT have a stroke command
        let svg = r#"
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24">
                <path d="M10 8 L18 12 L10 16 Z" fill="white"/>
            </svg>
        "#;

        let doc = SvgDocument::from_str(svg).unwrap();
        let commands = doc.commands();

        // Should have exactly 1 command (fill only)
        let fill_count = commands
            .iter()
            .filter(|c| matches!(c, SvgDrawCommand::FillPath { .. }))
            .count();
        let stroke_count = commands
            .iter()
            .filter(|c| matches!(c, SvgDrawCommand::StrokePath { .. }))
            .count();

        assert_eq!(fill_count, 1, "Should have exactly 1 fill command");
        assert_eq!(
            stroke_count, 0,
            "Should have NO stroke commands when stroke is not specified"
        );
    }
}