img_svg#
SVG images and icons: parsed once, drawn at any size through gfx's paths (the format IMGF_SVG) -- crate root lib/img_svg/lib.rs
img_svg -- SVG images and icons: a practical SVG 1.1 / SVG Tiny subset parsed once and drawn
at any size through gfx's path rasterizer (no libc, no std)
Svg::parse(bytes) -> Ok(svg) / Err(ERR_*) UTF-8 XML, or gzip (.svgz)
svg.size() -> (w, h) intrinsic size in px (width / height, else the viewBox, else
300 x 150); view_box(), title(), truncated(), element_count()
svg.render(sf, &m, clip, &mut opts) the document at its intrinsic size through
the matrix m (intrinsic px -> surface px), only inside clip
svg.render_rect(sf, x, y, w, h, clip, &mut opts) the rectangle is the viewport: the
viewBox is mapped into it (preserveAspectRatio)
svg.rasterize(w, h, &mut opts) -> Ok(Surface) a new FMT_PARGB surface of that size
Opts { color (currentColor), text: Option<&mut dyn TextHook> } (Opts::default(): black,
no text)
rasterize(bytes, w, h) -> Ok(Surface) parse + rasterize (w or h 0: from the aspect
ratio; both 0: the intrinsic size)
sniff(bytes) -> bool an SVG document (after BOM, XML declaration, comments, DOCTYPE)
register() the format IMGF_SVG ("svg;svgz") in img_core's format table:
img_core::io::load / load_ex / decode_ex read SVG files at
their intrinsic size (ui's runtime calls it at start-up)
CODEC the codec descriptor (decode, classic decode_fl, probe)
Supported: svg (nested: viewport, viewBox, preserveAspectRatio, overflow), g, defs, use
(+ symbol), switch (first child), a; path (all commands incl. arcs), rect (rx / ry), circle,
ellipse, line, polyline, polygon; transform (matrix translate scale rotate skewX skewY);
fill / stroke: colours (#rgb, #rrggbb(aa), rgb(a), hsl(a), 148 names, currentColor,
transparent), fill-opacity, fill-rule, stroke-width / -linecap / -linejoin / -miterlimit /
-dasharray / -dashoffset / -opacity; linearGradient / radialGradient (stops with offset,
stop-color, stop-opacity; gradientUnits, gradientTransform, spreadMethod pad / reflect /
repeat, href inheritance, focal point fx / fy / fr); opacity of groups and elements
(layers); visibility, display; clipPath (shapes, text, use; clipPathUnits, clip-rule,
nested clip paths); <style> sheets with type / class / id / attribute selectors and
descendant / child combinators, the style attribute, presentation attributes, inherit;
lengths in px pt pc mm cm in em ex %; text / tspan through a TextHook (one line per chunk,
x / y / dx / dy first values, text-anchor, font-size / -family / -weight / -style); image
with data: URIs of the registered raster formats (PNG, JPEG, ...).
Not supported (drawn without): pattern (the fallback colour), mask, marker, filter,
textPath layout, per-glyph positions, letter-spacing, external references (other files),
CSS pseudo-classes, @media, animation, scripts.
Robustness: malformed input never panics. The reader is forgiving (xml.rs); limits:
MAX_INPUT bytes (also after inflating), 250 000 elements, 256 levels, 4096 CSS rules, a
step budget for selector matching, 128 MB of declarations copied by the cascade (beyond:
ERR_LIMIT), 1 000 000 element visits and a work budget (pixels painted, layers and masks,
path points, children walked: 64 per pixel drawn, at least 2^26) per render, 64 levels of
nesting while drawing, use cycles cut, 8 layers alive at once.
img_svg crate root#
/// the largest document (bytes; also the inflated size of .svgz)
MAX_INPUT: usize = 32 << 20
fn sniff_at(data: &[u8]) -> Option<usize>the offset of the root element's '<' when data is an SVG document: BOM, blanks, the XML declaration, comments, processing instructions and a DOCTYPE may come first (4 KB of them)fn sniff(data: &[u8]) -> booldata is an SVG document (see sniff_at)static CODEC: Codecthe codec descriptor of SVG (IMGF_SVG)fn register() -> i32enter SVG into img_core's format table (IMGF_SVG, "svg;svgz=SVG", image/svg+xml)fn rasterize(data: &[u8], w: i32, h: i32) -> Result<Surface, i32>parse and draw: w x h px (w or h 0: from the other and the aspect ratio; both 0: the intrinsic size, rounded up)
img_svg/doc.rs#
Source: lib/img_svg/doc.rs
doc -- the parsed document: elements with their kind, attributes, cascaded properties,
pre-built path data, the id map, the intrinsic size and the embedded raster images
The cascade runs once at parse time: presentation attributes, then the matching rules of
every <style> sheet (by specificity, then order), then the style attribute; later
declarations win. Inheritance and "inherit" are resolved while rendering (render.rs),
because `use` makes an element inherit from the referencing element.
struct Svga parsed SVG document (immutable; render it as often as needed)
impl Svg
fn parse(data: &[u8]) -> Result<Svg, i32>parse an SVG document (UTF-8 XML; gzip data (.svgz) is inflated first): Err(ERR_HDR) when it is no SVG, ERR_LIMIT beyond the size limitsfn size(&self) -> (f64, f64)the intrinsic size in px (CSS px = DIP): width / height of the root, else its viewBox, else 300 x 150fn view_box(&self) -> Option<[f64; 4]>the root's viewBox (x, y, w, h), if it has onefn title(&self) -> &strthe text of the root's <title> (blanks collapsed; empty without one)fn truncated(&self) -> boolthe file ended early or a limit dropped elements (what was read is drawn)fn element_count(&self) -> usizethe number of elements
img_svg/render.rs#
Source: lib/img_svg/render.rs
render -- draw a parsed document through gfx: styles with inheritance, the element walk
(svg, g, a, switch, use + symbol, shapes, text, image), paints (colours, gradients),
group opacity in layers, clip paths as 8-bit masks
Coordinates: every element is drawn with the matrix user space -> device pixels; paths are
flattened in device space (gfx::pathdata, 0.05 px), strokes are outlined there by
gfx::dash (width = stroke-width x sqrt(|det|) of the matrix: non-uniform scaling draws an
even width), filled by gfx::raster with the fill rule. Opacity of an element that paints
one thing (only fill or only stroke) multiplies that paint; groups and elements that paint
both are drawn into a layer (the bounds of the content, inside the clip) and composited.
Text needs a TextHook (the app's font engine): one line per text chunk, tspans with their
own style and x / y / dx / dy (first values), text-anchor; without a hook text is skipped.
Limits: MAX_DRAWS element visits per render, MAX_NEST nesting (groups, use), MAX_LAYERS
layers alive at once (deeper opacity is applied to the paints), use cycles are cut; the work
of a render (pixels painted, layers, masks and images allocated, path points filled and
walked, children and text walked) is bounded by WORK_PER_PX per pixel of the drawn area, at
least MIN_WORK: a use DAG multiplies visits, each may cover the whole surface.
trait TextHookthe font engine for <text> (an app's; ui::SvgText wraps the UI's): glyph outlines and advances of one linefn outline(&mut self, path: &mut Path, s: &str, font: &FontSpec, px: f32, x: f32, y: f32) -> f32append the outline ofstopath(flattened closed contours in path pixels): the baseline starts at (x, y),pxpixels per em; returns the advance in pixelsfn advance(&mut self, s: &str, font: &FontSpec, px: f32) -> f32the advance ofsin pixels atpxpixels per em
struct FontSpec<'a>what a text run asks of the font enginefamily: &'a str-- the font-family list as written ("Arial, sans-serif")weight: u16-- 100 .. 900 (400 normal, 700 bold)italic: bool
struct Opts<'a>render optionscolor: u32-- the colour of currentColor at the root (0xAARRGGBB)text: Option<&'a mut dyn TextHook>-- the font engine for text (None: text is not drawn)
impl Svg
fn render(&self, sf: &mut Surface, m: &Matrix, clip: Option<[i32; 4]>, opts: &mut Opts)draw the document: its viewport (the intrinsic size, viewBox mapped by preserveAspectRatio) through m (intrinsic px -> surface px); clip: the surface rectangle x0, y0, x1, y1 (exclusive) that may change (None: all of it). Content outside the viewport is clipped (to its box under m). The surface: FMT_PARGB, or the window's FMT_XRGB (blended the same way)fn render_rect(&self, sf: &mut Surface, x: f64, y: f64, w: f64, h: f64, clip: Option<[i32; 4]>, opts: &mut Opts)draw the document into the rectangle x, y, w, h of the surface as its viewport (the viewBox mapped into it by preserveAspectRatio: sharp at any size)fn rasterize(&self, w: i32, h: i32, opts: &mut Opts) -> Result<Surface, i32>a new FMT_PARGB surface w x h with the document drawn into it (render_rect); Err(ERR_DIMS) for sides outside 1 .. 65535, Err(ERR_LIMIT) beyond IMG_MAXPX_DEF pixels