Documentation
¶
Overview ¶
Package svg2ivg converts SVG documents into IconVG, the compact vector format that gioui.org/widget.Icon renders:
data, err := svg2ivg.ConvertFile("arrow-left.svg", svg2ivg.Options{})
icon, err := widget.NewIcon(data)
Convert is the whole of the conversion API. Everything else here is batch plumbing on top of it: SVGFiles expands a set of paths, and Generate and Preview run the results through code generation and a contact sheet.
Generate exists because a Go program usually wants its artwork inside the binary rather than beside it. It writes a source file declaring one IconVG string constant per icon, so the program embeds the icon data as ordinary string literals and never parses XML — or opens a file — at run time. Converting artwork that arrives while the program is running works just as well, at the cost of linking the SVG reader into the binary; see CacheKey.
SVG is read with github.com/tdewolff/canvas. The supported subset includes shapes, groups, transforms, units, CSS colors, gradients, strokes, dashes and text. Known unsupported constructs are reported as errors rather than deliberately dropped. See the package README for details and limitations.
Conversion is reproducible except for <text>, whose fonts resolve against the machine's own font directories unless Options.FontDirs says otherwise.
Index ¶
- Constants
- func CacheKey(src []byte, opts Options) string
- func Convert(r io.Reader, opts Options) ([]byte, error)
- func ConvertFile(path string, opts Options) ([]byte, error)
- func Generate(w io.Writer, files []string, opts Options) error
- func GenerateDir(w io.Writer, dir string, opts Options) error
- func GenerateFile(out, dir string, opts Options) error
- func GenerateIcons(w io.Writer, icons []Icon, opts Options) error
- func Ident(path string) string
- func Preview(w io.Writer, files []string, opts Options) error
- func PreviewDir(w io.Writer, dir string, opts Options) error
- func PreviewFile(out, dir string, opts Options) error
- func PreviewIcons(w io.Writer, icons []Icon) error
- func SVGFiles(paths ...string) ([]string, error)
- func SVGFilesRecursive(paths ...string) ([]string, error)
- type Icon
- type InternalError
- type Options
- type Unsupported
Constants ¶
const DefaultSize = 48
DefaultSize is the IconVG output size used when Options.Size is zero. It matches the Material Design icon set.
Variables ¶
This section is empty.
Functions ¶
func CacheKey ¶
CacheKey returns a stable key for src and the options that affect Convert. Repeating the same request shares a key, so it suits a program converting the same artwork more than once — which build-time generation never does, and a program converting SVG that arrived at run time usually does. Different SVG source bytes may have different keys even when they produce identical IconVG.
The key covers only the four options Convert reads, so varying the ones that configure code generation does not cause a spurious miss. It does not cover the converter itself: upgrading svg2ivg can change the bytes a key maps to, which makes this safe for a cache held in memory and unsafe for one that outlives the process.
Cache the decoded gioui.org/widget.Icon rather than these bytes. Conversion costs microseconds, but an Icon caches its most recent rasterisation, so building a fresh one each frame throws that away and decodes, rasterises and re-uploads a texture every frame — far and away the larger cost:
key := svg2ivg.CacheKey(src, opts)
icon, ok := cache[key]
if !ok {
data, err := svg2ivg.Convert(bytes.NewReader(src), opts)
if err != nil {
return err
}
if icon, err = widget.NewIcon(data); err != nil {
return err
}
cache[key] = icon
}
func Convert ¶
Convert reads one SVG document and returns it encoded as IconVG, in the FFV0 encoding that gioui.org/widget.NewIcon decodes.
Only Options.Size, Options.KeepColors, Options.FontDirs and Options.NoText apply; the rest configure code generation.
Known unsupported constructs such as raster images, filters, soft masks and clip paths are reported as errors rather than deliberately dropped. Other documented SVG-to-IconVG limitations can still be lossy; see the README.
<text> is converted to outlines. Font families resolve against Options.FontDirs, or against the system fonts when that is empty — in which case the same SVG can convert differently on a machine with different fonts installed. Options.NoText rejects text outright.
Every panic the SVG reader and the geometry beneath it can throw is returned as an error instead, so converting artwork that arrived at run time cannot take the program down. See InternalError.
func ConvertFile ¶
ConvertFile is Convert reading from the named file.
func Generate ¶
Generate converts each named SVG file and writes the generated Go source to w. The output is gofmt'd. An unconvertible file fails the whole run rather than being skipped, so a broken asset cannot silently vanish from the generated package.
func GenerateDir ¶
GenerateDir converts every .svg file directly inside dir and writes the generated Go source to w. Files are processed in lexical order so output is stable across runs.
func GenerateFile ¶
GenerateFile is GenerateDir writing to the file named out, which is created or truncated, along with any directories leading to it.
func GenerateIcons ¶
GenerateIcons is Generate over icons that have already been converted. Only Options.Package, Options.Notice and Options.ByteSlices apply; the rest were read when the icons were converted.
func Ident ¶
Ident derives an exported Go identifier from an SVG file path: "arrow-left.svg" becomes "ArrowLeft". A name that would otherwise start with a digit is prefixed with "X" — "2x-zoom.svg" becomes "X2xZoom" — since Go identifiers cannot.
Generate applies Options.Prefix before that patch-up, so with a prefix of "Icon" the same file becomes Icon2xZoom rather than IconX2xZoom.
func Preview ¶
Preview converts each named SVG file and writes a PNG contact sheet of the results to w: every icon rasterized from its own IconVG encoding, labelled with the identifier Generate would give it.
Rasterizing what was encoded, rather than the SVG that went in, is the point. Strokes become filled outlines and text becomes glyph geometry during conversion, and neither transformation reports its own inaccuracy — the output is well-formed IconVG whether or not it still looks like the artwork. A contact sheet is the only way to see that.
Icons are drawn in the colours they carry. A themeable icon shows the colour its suggested palette was seeded with, which is the colour it was drawn in, not the colour gioui.org/widget.Icon will paint it.
func PreviewDir ¶
PreviewDir is Preview over every .svg file directly inside dir.
func PreviewFile ¶
PreviewFile is PreviewDir writing to the file named out, which is created or truncated, along with any directories leading to it.
func PreviewIcons ¶
PreviewIcons is Preview over icons that have already been converted. No option applies: everything the sheet shows was decided when they were.
func SVGFiles ¶
SVGFiles expands a mix of file and directory paths into the list of SVG files they name. A path to a file is taken as given, whatever its extension, since naming it is explicit enough. A directory contributes the .svg files directly inside it; the walk stops there, because a nested directory is as likely to be somebody else's icon set as more of this one. SVGFilesRecursive descends.
A directory holding no .svg files is an error rather than an empty contribution: naming one is a typo far more often than it is a request to convert nothing.
The result is sorted and deduplicated, so passing both a directory and a file inside it converts that file once, and the output does not depend on the order the paths were given in.
func SVGFilesRecursive ¶
SVGFilesRecursive is SVGFiles with every directory walked all the way down rather than one level deep. A directory whose tree holds no .svg file at any depth is the error case.
Symbolic links to directories are not followed, so an icon set cannot be walked twice or forever.
Types ¶
type Icon ¶
type Icon struct {
// Source is the path the artwork was read from.
Source string
// Name is the Go identifier, Options.Prefix already applied.
Name string
// Data is the IconVG encoding, as Convert returns it.
Data []byte
}
Icon is one converted file: where the artwork came from, the identifier Generate declares it under, and its IconVG encoding. ConvertFiles produces them, and GenerateIcons and PreviewIcons consume them.
func ConvertFiles ¶
ConvertFiles converts each named SVG file, in lexical order so that whatever is written from the result is stable however the caller listed them. An unconvertible file fails the whole run rather than being skipped, so a broken asset cannot silently vanish from the output.
Reach for this when the same icons are written more than once — a generated source file and a contact sheet, say. Generate and Preview each convert what they are given, so calling both on one file list converts everything twice.
type InternalError ¶
type InternalError struct {
// Value is what was passed to panic.
Value any
// Stack is the stack trace as of the panic.
Stack []byte
}
InternalError reports a panic that escaped the SVG reader or the geometry code beneath it. It means the converter hit a case it does not handle, not that the SVG is invalid: an SVG that fails this way is worth reporting at https://github.com/Randomblock1/svg2ivg/issues, with Stack attached.
func (*InternalError) Error ¶
func (e *InternalError) Error() string
type Options ¶
type Options struct {
// Package is the package clause of the generated file. Required by
// Generate, ignored by Convert.
Package string
// Size is the length, in IconVG units, of the longer side of the output
// graphic. Zero means DefaultSize. IconVG is resolution independent, so
// this sets coordinate precision rather than a rendered size.
Size float32
// Prefix is prepended to every generated identifier, e.g. "Icon" turns
// star.svg into IconStar. It must begin with an upper-case letter or digit.
Prefix string
// KeepColors emits every fill as a literal colour. By default an icon
// drawn in a single colour instead refers to palette entry 0, which
// gioui.org/widget.Icon replaces with the colour passed to Layout, so the
// icon follows the surrounding theme.
KeepColors bool
// FontDirs are the directories <text> font families resolve against. When
// empty the system font directories are used, which makes conversion
// depend on what is installed on the machine running it; pointing this at
// fonts committed alongside the assets makes the output reproducible.
FontDirs []string
// NoText rejects any SVG containing <text> instead of converting it to
// outlines. Use it to guarantee that no output can depend on locally
// installed fonts.
NoText bool
// Notice is emitted as a comment block below the generated-code header,
// before the package clause. Vendoring third-party artwork usually means
// carrying its copyright notice and license along with it; this is where
// they go. Typically the contents of the LICENSE file shipped with the
// icon set.
Notice string
// ByteSlices emits each icon as a mutable []byte variable rather than a
// string constant, matching what gioui.org/widget.NewIcon takes and saving
// the []byte(...) conversion at the call site. It costs the two things that
// make constants the default: a string literal is one token to the compiler
// where a list of bytes is one per byte, and only a constant can live in the
// binary's read-only segment. Being unwritable is a third benefit rather
// than the reason.
ByteSlices bool
}
Options configures conversion and code generation.
type Unsupported ¶
type Unsupported struct {
// Feature names the offending element or attribute, e.g. "<image>".
Feature string
// Reason explains why it cannot be converted.
Reason string
}
Unsupported reports an SVG feature that has no IconVG representation, or that the converter would otherwise have dropped without saying so. Conversion fails rather than emitting an icon that is quietly missing artwork.
func (*Unsupported) Error ¶
func (e *Unsupported) Error() string
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
svg2ivg
command
Command svg2ivg converts SVG files into IconVG, the compact vector format that gioui.org/widget.Icon renders.
|
Command svg2ivg converts SVG files into IconVG, the compact vector format that gioui.org/widget.Icon renders. |
|
internal
|
|
|
convert
Package convert turns one SVG document into an IconVG graphic, in the FFV0 encoding that gioui.org/widget.NewIcon decodes.
|
Package convert turns one SVG document into an IconVG graphic, in the FFV0 encoding that gioui.org/widget.NewIcon decodes. |
|
gogen
Package gogen writes the Go source file that declares the converted icons.
|
Package gogen writes the Go source file that declares the converted icons. |
|
ivgerr
Package ivgerr is the vocabulary for reporting SVG features that have no IconVG representation.
|
Package ivgerr is the vocabulary for reporting SVG features that have no IconVG representation. |
|
outfile
Package outfile writes what a generator produced to a file.
|
Package outfile writes what a generator produced to a file. |
|
prepass
Package prepass rewrites an SVG document into an equivalent one that github.com/tdewolff/canvas's SVG reader renders faithfully, and reports an error for anything it would render wrongly or drop.
|
Package prepass rewrites an SVG document into an equivalent one that github.com/tdewolff/canvas's SVG reader renders faithfully, and reports an error for anything it would render wrongly or drop. |
|
sheet
Package sheet lays out rasterized IconVG graphics as a labelled contact sheet.
|
Package sheet lays out rasterized IconVG graphics as a labelled contact sheet. |