forked from rustyoz/svg
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsvg.go
336 lines (297 loc) · 7.67 KB
/
svg.go
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
package svg
import (
"encoding/xml"
"errors"
"fmt"
"io"
"strconv"
"strings"
"sync"
mt "github.com/smallpdf/Mtransform"
)
// DrawingInstructionParser allow getting segments and drawing
// instructions from them. All SVG elements should implement this
// interface.
type DrawingInstructionParser interface {
ParseDrawingInstructions() (chan *DrawingInstruction, chan error)
}
// Tuple is an X,Y coordinate
type Tuple [2]float64
// Svg represents an SVG file containing at least a top level group or a
// number of Paths
type Svg struct {
Title string `xml:"title"`
Groups []Group `xml:"g"`
ViewBox string `xml:"viewBox,attr"`
Elements []DrawingInstructionParser
Name string
Transform *mt.Transform
scale float64
instructions chan *DrawingInstruction
errors chan error
segments chan Segment
}
// Group represents an SVG group (usually located in a 'g' XML element)
type Group struct {
ID string
Stroke string
StrokeWidth int32
Fill string
FillRule string
Elements []DrawingInstructionParser
TransformString string
Transform *mt.Transform // row, column
Parent *Group
Owner *Svg
instructions chan *DrawingInstruction
errors chan error
segments chan Segment
}
// ParseDrawingInstructions implements the DrawingInstructionParser interface
//
// This method makes it easier to get all the drawing instructions.
func (g *Group) ParseDrawingInstructions() (chan *DrawingInstruction, chan error) {
g.instructions = make(chan *DrawingInstruction, 100)
g.errors = make(chan error, 100)
errWg := &sync.WaitGroup{}
go func() {
defer close(g.instructions)
defer func() { errWg.Wait(); close(g.errors) }()
for _, e := range g.Elements {
instrs, errs := e.ParseDrawingInstructions()
errWg.Add(1)
go func() {
for er := range errs {
g.errors <- er
}
errWg.Done()
}()
for is := range instrs {
g.instructions <- is
}
}
}()
return g.instructions, g.errors
}
// UnmarshalXML implements the encoding.xml.Unmarshaler interface
func (g *Group) UnmarshalXML(decoder *xml.Decoder, start xml.StartElement) error {
for _, attr := range start.Attr {
switch attr.Name.Local {
case "id":
g.ID = attr.Value
case "stroke":
g.Stroke = attr.Value
case "stroke-width":
intValue, err := strconv.ParseInt(attr.Value, 10, 32)
if err != nil {
return err
}
g.StrokeWidth = int32(intValue)
case "fill":
g.Fill = attr.Value
case "fill-rule":
g.FillRule = attr.Value
case "transform":
g.TransformString = attr.Value
t, err := parseTransform(g.TransformString)
if err != nil {
fmt.Println(err)
}
g.Transform = &t
}
}
for {
token, err := decoder.Token()
if err != nil {
return err
}
switch tok := token.(type) {
case xml.StartElement:
var elementStruct DrawingInstructionParser
switch tok.Name.Local {
case "g":
elementStruct = &Group{Parent: g, Owner: g.Owner, Transform: mt.NewTransform()}
case "rect":
elementStruct = &Rect{group: g}
case "circle":
elementStruct = &Circle{group: g}
case "path":
elementStruct = &Path{group: g, StrokeWidth: float64(g.StrokeWidth), Stroke: &g.Stroke, Fill: &g.Fill}
default:
continue
}
if err = decoder.DecodeElement(elementStruct, &tok); err != nil {
return fmt.Errorf("error decoding element of Group: %s", err)
}
g.Elements = append(g.Elements, elementStruct)
case xml.EndElement:
if tok.Name.Local == "g" {
return nil
}
}
}
}
// ParseDrawingInstructions implements the DrawingInstructionParser interface
//
// This method makes it easier to get all the drawing instructions.
func (s *Svg) ParseDrawingInstructions() (chan *DrawingInstruction, chan error) {
s.instructions = make(chan *DrawingInstruction, 100)
s.errors = make(chan error, 100)
go func() {
errWg := &sync.WaitGroup{}
var elecount int
defer close(s.instructions)
defer func() { errWg.Wait(); close(s.errors) }()
for _, e := range s.Elements {
elecount++
instrs, errs := e.ParseDrawingInstructions()
errWg.Add(1)
go func(count int) {
for er := range errs {
s.errors <- fmt.Errorf("error when parsing element nr. %d: %s", count, er)
}
errWg.Done()
}(elecount)
for is := range instrs {
s.instructions <- is
}
}
for _, g := range s.Groups {
instrs, errs := g.ParseDrawingInstructions()
errWg.Add(1)
go func() {
for er := range errs {
s.errors <- er
}
errWg.Done()
}()
for is := range instrs {
s.instructions <- is
}
}
}()
return s.instructions, s.errors
}
// UnmarshalXML implements the encoding.xml.Unmarshaler interface
func (s *Svg) UnmarshalXML(decoder *xml.Decoder, start xml.StartElement) error {
for {
for _, attr := range start.Attr {
if attr.Name.Local == "viewBox" {
s.ViewBox = attr.Value
break
}
}
token, err := decoder.Token()
if err != nil {
return err
}
switch tok := token.(type) {
case xml.StartElement:
var dip DrawingInstructionParser
switch tok.Name.Local {
case "g":
g := &Group{Owner: s, Transform: mt.NewTransform()}
if err = decoder.DecodeElement(g, &tok); err != nil {
return fmt.Errorf("error decoding group element within SVG struct: %s", err)
}
s.Groups = append(s.Groups, *g)
continue
case "rect":
dip = &Rect{}
case "circle":
dip = &Circle{}
case "path":
dip = &Path{}
default:
continue
}
if err = decoder.DecodeElement(dip, &tok); err != nil {
return fmt.Errorf("error decoding element of SVG struct: %s", err)
}
s.Elements = append(s.Elements, dip)
case xml.EndElement:
if tok.Name.Local == "svg" {
return nil
}
}
}
}
// ParseSvg parses an SVG string into an SVG struct
func ParseSvg(str string, name string, scale float64) (*Svg, error) {
var svg Svg
svg.Name = name
svg.Transform = mt.NewTransform()
if scale > 0 {
svg.Transform.Scale(scale, scale)
svg.scale = scale
}
if scale < 0 {
svg.Transform.Scale(1.0/-scale, 1.0/-scale)
svg.scale = 1.0 / -scale
}
err := xml.Unmarshal([]byte(str), &svg)
if err != nil {
return nil, fmt.Errorf("ParseSvg Error: %v", err)
}
for i := range svg.Groups {
svg.Groups[i].SetOwner(&svg)
if svg.Groups[i].Transform == nil {
svg.Groups[i].Transform = mt.NewTransform()
}
}
return &svg, nil
}
// ParseSvgFromReader parses an SVG struct from an io.Reader
func ParseSvgFromReader(r io.Reader, name string, scale float64) (*Svg, error) {
var svg Svg
svg.Name = name
svg.Transform = mt.NewTransform()
if scale > 0 {
svg.Transform.Scale(scale, scale)
svg.scale = scale
}
if scale < 0 {
svg.Transform.Scale(1.0/-scale, 1.0/-scale)
svg.scale = 1.0 / -scale
}
if err := xml.NewDecoder(r).Decode(&svg); err != nil {
return nil, fmt.Errorf("ParseSvg Error: %v", err)
}
for i := range svg.Groups {
svg.Groups[i].SetOwner(&svg)
if svg.Groups[i].Transform == nil {
svg.Groups[i].Transform = mt.NewTransform()
}
}
return &svg, nil
}
// ViewBoxValues returns all the numerical values in the viewBox
// attribute.
func (s *Svg) ViewBoxValues() ([]float64, error) {
var vals []float64
if s.ViewBox == "" {
return vals, errors.New("viewBox attribute is empty")
}
split := strings.Split(s.ViewBox, " ")
for _, val := range split {
ival, err := strconv.ParseFloat(val, 64)
if err != nil {
return vals, err
}
vals = append(vals, ival)
}
return vals, nil
}
// SetOwner sets the owner of a SVG Group
func (g *Group) SetOwner(svg *Svg) {
g.Owner = svg
for _, gn := range g.Elements {
switch gn.(type) {
case *Group:
gn.(*Group).Owner = g.Owner
gn.(*Group).SetOwner(svg)
case *Path:
gn.(*Path).group = g
}
}
}