-
Notifications
You must be signed in to change notification settings - Fork 555
/
SVGParser.swift
2271 lines (2019 loc) · 83.4 KB
/
SVGParser.swift
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Foundation
import CoreGraphics
#if !CARTHAGE
import SWXMLHash
#endif
///
/// This class used to parse SVG file and build corresponding Macaw scene
///
open class SVGParser {
/// Parse an SVG file identified by the specified bundle, name and file extension.
///
/// - Parameters:
/// - bundle: Bundle resource
/// - path: Resource filename
/// - ofType: Type of resource file. The default is "svg"
/// - Returns: Root node of the corresponding Macaw scene.
/// - Throws: An SVGParserError of no such file
@available(*, deprecated)
open class func parse(bundle: Bundle, path: String, ofType: String = "svg") throws -> Node {
guard let fullPath = bundle.path(forResource: path, ofType: ofType) else {
throw SVGParserError.noSuchFile(path: "\(path).\(ofType)")
}
let text = try String(contentsOfFile: fullPath, encoding: .utf8)
return try SVGParser.parse(text: text)
}
/// Parse an SVG file identified by the specified name and file extension.
///
/// - Parameters:
/// - path: Resource filename
/// - ofType: Type of resource file. The default is "svg"
/// - Returns: Root node of the corresponding Macaw scene.
/// - Throws: An SVGParserError of no such file
@available(*, deprecated)
open class func parse(path: String, ofType: String = "svg") throws -> Node {
return try SVGParser.parse(bundle: Bundle.main, path: path, ofType: ofType)
}
/// Parse an SVG file
///
/// - Parameters:
/// - resource: Resource file name
/// - type: Type of resource file. The default is `svg`
/// - directory: Directory of given resource
/// - bundle: Bundle of given resource
/// - Returns: Root node of the corresponding Macaw scene.
/// - Throws: An SVGParserError of no such file
open class func parse(resource: String,
ofType type: String = "svg",
inDirectory directory: String? = nil,
fromBundle bundle: Bundle = Bundle.main) throws -> Node {
guard let fullpath = bundle.path(forResource: resource, ofType: type, inDirectory: directory) else {
throw SVGParserError.noSuchFile(path: "\(resource).\(type)")
}
return try SVGParser.parse(fullPath: fullpath)
}
/// Parse an SVG file identified by full file path
///
/// - Parameter fullPath: Full path
/// - Returns: Root node of the corresponding Macaw scene.
/// - Throws: An SVGParserError of no such file
open class func parse(fullPath: String) throws -> Node {
guard let text = try? String(contentsOfFile: fullPath, encoding: .utf8) else {
throw SVGParserError.noSuchFile(path: fullPath)
}
return try SVGParser.parse(text: text)
}
/// Parse the specified content of an SVG file.
/// - returns: Root node of the corresponding Macaw scene.
open class func parse(text: String) throws -> Node {
return try SVGParser(text).parse()
}
let availableStyleAttributes = ["stroke",
"stroke-width",
"stroke-opacity",
"stroke-dasharray",
"stroke-dashoffset",
"stroke-linecap",
"stroke-linejoin",
"stroke-miterlimit",
"fill",
"fill-rule",
"fill-opacity",
"clip-path",
"mask",
"opacity",
"color",
"stop-color",
"stop-opacity",
"font-family",
"font-size",
"font-weight",
"text-anchor",
"visibility",
"display"]
fileprivate let xmlString: String
fileprivate let initialPosition: Transform
fileprivate var nodes = [Node]()
fileprivate var defNodes = [String: XMLIndexer]()
fileprivate var defFills = [String: Fill]()
fileprivate var defMasks = [String: UserSpaceNode]()
fileprivate var defClip = [String: UserSpaceLocus]()
fileprivate var defEffects = [String: Effect]()
fileprivate var defPatterns = [String: UserSpacePattern]()
fileprivate var styles = CSSParser()
fileprivate enum PathCommandType {
case moveTo
case lineTo
case lineV
case lineH
case curveTo
case smoothCurveTo
case closePath
case none
}
fileprivate typealias PathCommand = (type: PathCommandType, expression: String, absolute: Bool)
fileprivate init(_ string: String, pos: Transform = Transform()) {
self.xmlString = string
self.initialPosition = pos
}
fileprivate func parse() throws -> Group {
let config = XMLHash.config { config in
config.shouldProcessNamespaces = true
}
let parsedXml = config.parse(xmlString)
var svgElement: XMLHash.XMLElement?
for child in parsedXml.children {
if let element = child.element {
if element.name == "svg" {
svgElement = element
try prepareSvg(child.children)
break
}
}
}
let layout = try svgElement.flatMap(parseViewBox)
try parseSvg(parsedXml.children)
let root = layout.flatMap { SVGCanvas(layout: $0, contents: nodes) } ?? Group(contents: nodes)
if let opacity = svgElement?.attribute(by: "opacity") {
root.opacity = getOpacity(opacity.text)
}
return root
}
fileprivate func prepareSvg(_ children: [XMLIndexer]) throws {
try children.forEach { child in
try prepareSvg(child)
}
}
fileprivate func prepareSvg(_ node: XMLIndexer) throws {
if let element = node.element {
if element.name == "style" {
parseStyle(node)
} else if element.name == "defs" || element.name == "g" {
try node.children.forEach { child in
try prepareSvg(child)
}
}
if let id = element.allAttributes["id"]?.text {
switch element.name {
case "linearGradient", "radialGradient", SVGKeys.fill:
defFills[id] = try parseFill(node)
case "pattern":
defPatterns[id] = try parsePattern(node)
case "mask":
defMasks[id] = try parseMask(node)
case "filter":
defEffects[id] = try parseEffect(node)
case "clip", "clipPath":
defClip[id] = try parseClip(node)
default:
defNodes[id] = node
}
}
}
}
fileprivate func parseSvg(_ children: [XMLIndexer]) throws {
try children.forEach { child in
if let element = child.element {
if element.name == "svg" {
try parseSvg(child.children)
} else if let node = try parseNode(child) {
self.nodes.append(node)
}
}
}
}
fileprivate func parseViewBox(_ element: XMLHash.XMLElement) throws -> SVGNodeLayout? {
let widthAttributeNil = element.allAttributes["width"] == nil
let heightAttributeNil = element.allAttributes["height"] == nil
let viewBoxAttributeNil = element.allAttributes["viewBox"] == nil
if widthAttributeNil && heightAttributeNil && viewBoxAttributeNil {
return .none
}
let w = getDimensionValue(element, attribute: "width") ?? SVGLength(percent: 100)
let h = getDimensionValue(element, attribute: "height") ?? SVGLength(percent: 100)
let svgSize = SVGSize(width: w, height: h)
var viewBox: Rect?
if let viewBoxString = element.allAttributes["viewBox"]?.text {
let nums = viewBoxString.components(separatedBy: .whitespaces).map { Double($0) }
if nums.count == 4, let x = nums[0], let y = nums[1], let w = nums[2], let h = nums[3] {
viewBox = Rect(x: x, y: y, w: w, h: h)
}
}
var xAligningMode, yAligningMode: Align?
var scalingMode: AspectRatio?
if let contentModeString = element.allAttributes["preserveAspectRatio"]?.text {
let strings = contentModeString.components(separatedBy: CharacterSet(charactersIn: " "))
if strings.count == 1 { // none
scalingMode = parseAspectRatio(strings[0])
return SVGNodeLayout(svgSize: svgSize, viewBox: viewBox, scaling: scalingMode)
}
guard strings.count == 2 else {
throw SVGParserError.invalidContentMode
}
let alignString = strings[0]
var xAlign = alignString.prefix(4).lowercased()
xAlign.remove(at: xAlign.startIndex)
xAligningMode = parseAlign(xAlign)
var yAlign = alignString.suffix(4).lowercased()
yAlign.remove(at: yAlign.startIndex)
yAligningMode = parseAlign(yAlign)
scalingMode = parseAspectRatio(strings[1])
}
return SVGNodeLayout(svgSize: svgSize,
viewBox: viewBox,
scaling: scalingMode,
xAlign: xAligningMode,
yAlign: yAligningMode)
}
fileprivate func parseNode(_ node: XMLIndexer, groupStyle: [String: String] = [:]) throws -> Node? {
var result: Node?
if let element = node.element {
let style = getStyleAttributes(groupStyle, element: element)
if style["display"] == "none" {
return .none
}
switch element.name {
case "g":
result = try parseGroup(node, style: style)
case "style", "defs":
// do nothing - it was parsed on first iteration
return .none
default:
result = try parseElement(node, style: style)
}
if let result = result,
let filterString = style["filter"],
let filterId = parseIdFromUrl(filterString),
let effect = defEffects[filterId] {
result.effect = effect
}
}
return result
}
fileprivate func parseStyle(_ styleNode: XMLIndexer) {
if let rawStyle = styleNode.element?.text {
styles.parse(content: rawStyle)
}
}
fileprivate func parseElement(_ node: XMLIndexer, style: [String: String]) throws -> Node? {
if style["visibility"] == "hidden" {
return .none
}
guard let element = node.element else {
return .none
}
let hasMask = style["mask"] != .none
let position = getPosition(element)
switch element.name {
case "path":
if var path = parsePath(node) {
let mask = try getMask(style, locus: path)
if let rule = getFillRule(style) {
path = Path(segments: path.segments, fillRule: rule)
}
if !hasMask || hasMask && mask != .none {
return Shape(form: path,
fill: getFillColor(style, groupStyle: style, locus: path),
stroke: getStroke(style, groupStyle: style),
place: position,
opacity: getOpacity(style),
clip: getClipPath(style, locus: path),
mask: mask,
tag: getTag(element))
}
}
case "line":
if let line = parseLine(node) {
let mask = try getMask(style, locus: line)
if !hasMask || hasMask && mask != .none {
return Shape(form: line,
fill: getFillColor(style, groupStyle: style, locus: line),
stroke: getStroke(style, groupStyle: style),
place: position,
opacity: getOpacity(style),
clip: getClipPath(style, locus: line),
mask: mask,
tag: getTag(element))
}
}
case "rect":
if let rect = parseRect(node) {
let mask = try getMask(style, locus: rect)
if !hasMask || hasMask && mask != .none {
return Shape(form: rect,
fill: getFillColor(style, groupStyle: style, locus: rect),
stroke: getStroke(style, groupStyle: style),
place: position,
opacity: getOpacity(style),
clip: getClipPath(style, locus: rect),
mask: mask,
tag: getTag(element))
}
}
case "circle":
if let circle = parseCircle(node) {
let mask = try getMask(style, locus: circle)
if !hasMask || hasMask && mask != .none {
return Shape(form: circle,
fill: getFillColor(style, groupStyle: style, locus: circle),
stroke: getStroke(style, groupStyle: style),
place: position,
opacity: getOpacity(style),
clip: getClipPath(style, locus: circle),
mask: mask,
tag: getTag(element))
}
}
case "ellipse":
if let ellipse = parseEllipse(node) {
let mask = try getMask(style, locus: ellipse)
if !hasMask || hasMask && mask != .none {
return Shape(form: ellipse,
fill: getFillColor(style, groupStyle: style, locus: ellipse),
stroke: getStroke(style, groupStyle: style),
place: position,
opacity: getOpacity(style),
clip: getClipPath(style, locus: ellipse),
mask: mask,
tag: getTag(element))
}
}
case "polygon":
if let polygon = parsePolygon(node) {
let mask = try getMask(style, locus: polygon)
if !hasMask || hasMask && mask != .none {
return Shape(form: polygon,
fill: getFillColor(style, groupStyle: style, locus: polygon),
stroke: getStroke(style, groupStyle: style),
place: position,
opacity: getOpacity(style),
clip: getClipPath(style, locus: polygon),
mask: mask,
tag: getTag(element))
}
}
case "polyline":
if let polyline = parsePolyline(node) {
let mask = try getMask(style, locus: polyline)
if !hasMask || hasMask && mask != .none {
return Shape(form: polyline,
fill: getFillColor(style, groupStyle: style, locus: polyline),
stroke: getStroke(style, groupStyle: style),
place: position,
opacity: getOpacity(style),
clip: getClipPath(style, locus: polyline),
mask: mask,
tag: getTag(element))
}
}
case "image":
return parseImage(node, opacity: getOpacity(style), pos: position, clip: getClipPath(style, locus: nil))
case "text":
return parseText(node,
textAnchor: getTextAnchor(style),
fill: getFillColor(style, groupStyle: style),
stroke: getStroke(style, groupStyle: style),
opacity: getOpacity(style),
fontName: getFontName(style),
fontSize: getFontSize(style),
fontWeight: getFontWeight(style),
pos: position)
case "use":
return try parseUse(node, groupStyle: style, place: position)
case "title", "desc", "mask", "clip", "filter",
"linearGradient", "radialGradient", SVGKeys.fill:
break
default:
print("SVG parsing error. Shape \(element.name) not supported")
return .none
}
return .none
}
fileprivate func parseFill(_ fill: XMLIndexer) throws -> Fill? {
guard let element = fill.element else {
return .none
}
let style = getStyleAttributes([:], element: element)
switch element.name {
case "linearGradient":
return parseLinearGradient(fill, groupStyle: style)
case "radialGradient":
return parseRadialGradient(fill, groupStyle: style)
default:
return .none
}
}
fileprivate func parsePattern(_ pattern: XMLIndexer) throws -> UserSpacePattern? {
guard let element = pattern.element else {
return .none
}
var parentPattern: UserSpacePattern?
if let link = element.allAttributes["xlink:href"]?.text.replacingOccurrences(of: " ", with: ""),
link.hasPrefix("#") {
let id = link.replacingOccurrences(of: "#", with: "")
parentPattern = defPatterns[id]
}
let x = getDoubleValue(element, attribute: "x") ?? parentPattern?.bounds.x ?? 0
let y = getDoubleValue(element, attribute: "y") ?? parentPattern?.bounds.y ?? 0
let w = getDoubleValue(element, attribute: "width") ?? parentPattern?.bounds.w ?? 0
let h = getDoubleValue(element, attribute: "height") ?? parentPattern?.bounds.h ?? 0
let bounds = Rect(x: x, y: y, w: w, h: h)
var userSpace = parentPattern?.userSpace ?? false
if let units = element.allAttributes["patternUnits"]?.text, units == "userSpaceOnUse" {
userSpace = true
}
var contentUserSpace = parentPattern?.contentUserSpace ?? true
if let units = element.allAttributes["patternContentUnits"]?.text, units == "objectBoundingBox" {
contentUserSpace = false
}
func parseContentNode() throws -> Node? {
if pattern.children.isEmpty {
return parentPattern?.content
} else if pattern.children.count == 1,
let child = pattern.children.first,
let shape = try parseNode(child) as? Shape {
return shape
} else {
var shapes = [Shape]()
try pattern.children.forEach { indexer in
if let shape = try parseNode(indexer) as? Shape {
shapes.append(shape)
}
}
return Group(contents: shapes)
}
}
guard let contentNode = try parseContentNode() else {
print("Pattern does not contain any content.")
return .none
}
return UserSpacePattern(content: contentNode,
bounds: bounds,
userSpace: userSpace,
contentUserSpace: contentUserSpace)
}
fileprivate func parseGroup(_ group: XMLIndexer, style: [String: String]) throws -> Group? {
guard let element = group.element else {
return .none
}
var groupNodes: [Node] = []
try group.children.forEach { child in
if let node = try parseNode(child, groupStyle: style) {
groupNodes.append(node)
}
}
return Group(contents: groupNodes, place: getPosition(element), tag: getTag(element))
}
fileprivate func getPosition(_ element: XMLHash.XMLElement) -> Transform {
guard let transformAttribute = element.allAttributes["transform"]?.text else {
return Transform.identity
}
return parseTransformationAttribute(transformAttribute)
}
fileprivate func parseAlign(_ string: String) -> Align {
if string == "min" {
return .min
}
if string == "mid" {
return .mid
}
return .max
}
fileprivate func parseAspectRatio(_ string: String) -> AspectRatio {
if string == "meet" {
return .meet
}
if string == "slice" {
return .slice
}
return .none
}
var count = 0
fileprivate func parseTransformationAttribute(_ attributes: String,
transform: Transform = Transform()) -> Transform {
// Transform attribute regular grammar (whitespace characters are ignored):
// ([a-zA-Z]+)\(((-?\d+\.?\d*e?-?\d*,?)+)\)
// Group (1) is an attribute name.
// Group (2) is comma-separated numbers.
var transform = transform
let scanner = Scanner(string: attributes)
stopParse: while !scanner.isAtEnd {
guard let attributeName = scanner.scannedCharacters(from: .transformationAttributeCharacters),
scanner.scannedString("(") != nil,
let valuesString = scanner.scannedUpToString(")"),
scanner.scannedString(")") != nil else {
break stopParse
}
// Skip an optional comma after ")".
_ = scanner.scannedString(",")
let values = parseTransformValues(valuesString)
if values.isEmpty {
return transform
}
switch attributeName {
case "translate":
let x = values[0]
var y: Double = 0
if values.indices ~= 1 {
y = values[1]
}
transform = transform.move(dx: x, dy: y)
case "scale":
let x = values[0]
var y: Double = x
if values.indices ~= 1 {
y = values[1]
}
transform = transform.scale(sx: x, sy: y)
case "rotate":
let angle = values[0]
if values.count == 1 {
transform = transform.rotate(angle: degreesToRadians(angle))
} else if values.count == 3 {
let x = values[1]
let y = values[2]
transform = transform
.move(dx: x, dy: y)
.rotate(angle: degreesToRadians(angle))
.move(dx: -x, dy: -y)
}
case "skewX":
let x = values[0]
let v = tan((x * Double.pi) / 180.0)
transform = transform.shear(shx: v, shy: 0)
case "skewY":
let y = values[0]
let v = tan((y * Double.pi) / 180.0)
transform = transform.shear(shx: 0, shy: v)
case "matrix":
if values.count != 6 {
return transform
}
let m11 = values[0]
let m12 = values[1]
let m21 = values[2]
let m22 = values[3]
let dx = values[4]
let dy = values[5]
let transformMatrix = Transform(m11: m11, m12: m12, m21: m21, m22: m22, dx: dx, dy: dy)
transform = transform.concat(with: transformMatrix)
default:
break stopParse
}
}
return transform
}
/// Parse an RGB
/// - returns: Color for the corresponding SVG color string in RGB notation.
fileprivate func parseRGBNotation(colorString: String) -> Color {
let from = colorString.index(colorString.startIndex, offsetBy: 4)
let inPercentage = colorString.contains("%")
let sp = String(colorString.suffix(from: from))
.replacingOccurrences(of: "%", with: "")
.replacingOccurrences(of: ")", with: "")
.replacingOccurrences(of: " ", with: "")
let x = sp.components(separatedBy: ",")
var red = 0.0
var green = 0.0
var blue = 0.0
if x.count == 3 {
if let r = Double(x[0]), let g = Double(x[1]), let b = Double(x[2]) {
blue = b
green = g
red = r
}
}
if inPercentage {
red *= 2.55
green *= 2.55
blue *= 2.55
}
return Color.rgb(r: Int(red.rounded(.up)),
g: Int(green.rounded(.up)),
b: Int(blue.rounded(.up)))
}
fileprivate func parseTransformValues(_ values: String) -> [Double] {
// Parse comma-separated list of numbers.
var collectedValues: [Double] = []
let scanner = Scanner(string: values)
while !scanner.isAtEnd {
if let value = scanner.scannedDouble() {
collectedValues.append(value)
} else {
break
}
_ = scanner.scannedString(",")
}
return collectedValues
}
fileprivate func getStyleAttributes(_ groupAttributes: [String: String],
element: XMLHash.XMLElement) -> [String: String] {
var styleAttributes: [String: String] = groupAttributes
for (att, val) in styles.getStyles(element: element) {
if styleAttributes.index(forKey: att) == nil {
styleAttributes.updateValue(val, forKey: att)
}
}
if let style = element.allAttributes["style"]?.text {
let styleParts = style.replacingOccurrences(of: " ", with: "").components(separatedBy: ";")
styleParts.forEach { styleAttribute in
let currentStyle = styleAttribute.components(separatedBy: ":")
if currentStyle.count == 2 {
styleAttributes.updateValue(currentStyle[1], forKey: currentStyle[0])
}
}
}
let hasCurrentColor = styleAttributes[SVGKeys.fill] == SVGKeys.currentColor
self.availableStyleAttributes.forEach { availableAttribute in
if let styleAttribute = element.allAttributes[availableAttribute]?.text, styleAttribute != "inherit" {
if !hasCurrentColor || availableAttribute != SVGKeys.color {
styleAttributes.updateValue(styleAttribute, forKey: availableAttribute)
}
}
}
return styleAttributes
}
fileprivate func createColorFromHex(_ hexString: String, opacity: Double = 1) -> Color {
var cleanedHexString = hexString
if hexString.hasPrefix("#") {
cleanedHexString = hexString.replacingOccurrences(of: "#", with: "")
}
if cleanedHexString.count == 3 {
let x = Array(cleanedHexString)
cleanedHexString = "\(x[0])\(x[0])\(x[1])\(x[1])\(x[2])\(x[2])"
}
var rgbValue: UInt32 = 0
if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *), let scannedInt = Scanner(string: cleanedHexString).scanUInt64(representation: .hexadecimal) {
rgbValue = UInt32(scannedInt)
} else {
Scanner(string: cleanedHexString).scanHexInt32(&rgbValue)
}
let red = CGFloat((rgbValue >> 16) & 0xff)
let green = CGFloat((rgbValue >> 08) & 0xff)
let blue = CGFloat((rgbValue >> 00) & 0xff)
return Color.rgba(r: Int(red), g: Int(green), b: Int(blue), a: opacity)
}
fileprivate func createColor(_ colorString: String, opacity: Double = 1) -> Color? {
if colorString == "none" || colorString == "transparent" {
return .none
}
let opacity = min(max(opacity, 0), 1)
if let defaultColor = SVGConstants.colorList[colorString] {
let color = Color(val: defaultColor)
return opacity != 1 ? color.with(a: opacity) : color
}
if let systemColor = SVGConstants.systemColorList[colorString] {
let color = Color(val: systemColor)
return opacity != 1 ? color.with(a: opacity) : color
}
if colorString.hasPrefix("rgb") {
let color = parseRGBNotation(colorString: colorString)
return opacity != 1 ? color.with(a: opacity) : color
}
return createColorFromHex(colorString, opacity: opacity)
}
fileprivate func getFillColor(_ styleParts: [String: String],
groupStyle: [String: String] = [:],
locus: Locus? = nil) -> Fill? {
var opacity: Double = 1
if let fillOpacity = styleParts["fill-opacity"] {
opacity = Double(fillOpacity.replacingOccurrences(of: " ", with: "")) ?? 1
}
guard var fillColor = styleParts[SVGKeys.fill] else {
return Color.black.with(a: opacity)
}
if let colorId = parseIdFromUrl(fillColor) {
if let fill = defFills[colorId] {
return fill
}
if let pattern = defPatterns[colorId] {
return getPatternFill(pattern: pattern, locus: locus)
}
}
if fillColor == SVGKeys.currentColor, let currentColor = groupStyle[SVGKeys.color] {
fillColor = currentColor
}
return createColor(fillColor.replacingOccurrences(of: " ", with: ""), opacity: opacity)
}
fileprivate func getPatternFill(pattern: UserSpacePattern, locus: Locus?) -> Pattern {
if let locus = locus, pattern.userSpace == false && pattern.contentUserSpace == true {
let tranform = BoundsUtils.transformForLocusInRespectiveCoords(respectiveLocus: pattern.bounds,
absoluteLocus: locus)
return Pattern(content: pattern.content, bounds: pattern.bounds.applying(tranform), userSpace: true)
}
if let locus = locus, pattern.userSpace == true && pattern.contentUserSpace == false {
if let patternNode = BoundsUtils.createNodeFromRespectiveCoords(respectiveNode: pattern.content,
absoluteLocus: locus) {
return Pattern(content: patternNode, bounds: pattern.bounds, userSpace: pattern.userSpace)
}
}
return Pattern(content: pattern.content, bounds: pattern.bounds, userSpace: true)
}
fileprivate func getStroke(_ styleParts: [String: String], groupStyle: [String: String] = [:]) -> Stroke? {
guard var strokeColor = styleParts["stroke"] else {
return .none
}
if strokeColor == SVGKeys.currentColor, let currentColor = groupStyle[SVGKeys.color] {
strokeColor = currentColor
}
var opacity: Double = 1
if let strokeOpacity = styleParts["stroke-opacity"] {
opacity = Double(strokeOpacity.replacingOccurrences(of: " ", with: "")) ?? 1
opacity = min(max(opacity, 0), 1)
}
var fill: Fill?
if let colorId = parseIdFromUrl(strokeColor) {
fill = defFills[colorId]
} else {
fill = createColor(strokeColor.replacingOccurrences(of: " ", with: ""), opacity: opacity)
}
if let strokeFill = fill {
return Stroke(fill: strokeFill,
width: getStrokeWidth(styleParts),
cap: getStrokeCap(styleParts),
join: getStrokeJoin(styleParts),
miterLimit: getStrokeMiterLimit(styleParts),
dashes: getStrokeDashes(styleParts),
offset: getStrokeOffset(styleParts))
}
return .none
}
fileprivate func getStrokeWidth(_ styleParts: [String: String]) -> Double {
if let strokeWidth = styleParts["stroke-width"], let value = doubleFromString(strokeWidth) {
return value
}
return 1
}
fileprivate func getStrokeMiterLimit(_ styleParts: [String: String]) -> Double {
if let strokeWidth = styleParts["stroke-miterlimit"], let value = doubleFromString(strokeWidth) {
return value
}
return 4
}
fileprivate func getStrokeCap(_ styleParts: [String: String]) -> LineCap {
var cap = LineCap.butt
if let strokeCap = styleParts["stroke-linecap"] {
switch strokeCap {
case "round":
cap = .round
case "butt":
cap = .butt
case "square":
cap = .square
default:
break
}
}
return cap
}
fileprivate func getStrokeJoin(_ styleParts: [String: String]) -> LineJoin {
var join = LineJoin.miter
if let strokeJoin = styleParts["stroke-linejoin"] {
switch strokeJoin {
case "round":
join = .round
case "miter":
join = .miter
case "bevel":
join = .bevel
default:
break
}
}
return join
}
fileprivate func getStrokeDashes(_ styleParts: [String: String]) -> [Double] {
var dashes = [Double]()
if let strokeDashes = styleParts["stroke-dasharray"] {
let separatedValues = strokeDashes.components(separatedBy: CharacterSet(charactersIn: " ,"))
separatedValues.forEach { value in
if let doubleValue = doubleFromString(value) {
dashes.append(doubleValue)
}
}
}
return dashes
}
fileprivate func getMatrix(_ element: XMLHash.XMLElement, attribute: String) -> [Double] {
var result = [Double]()
if let values = element.allAttributes[attribute]?.text {
let separatedValues = values.components(separatedBy: CharacterSet(charactersIn: " ,"))
separatedValues.forEach { value in
if let doubleValue = doubleFromString(value) {
result.append(doubleValue)
}
}
}
return result
}
fileprivate func getStrokeOffset(_ styleParts: [String: String]) -> Double {
if let strokeOffset = styleParts["stroke-dashoffset"], let offset = doubleFromString(strokeOffset) {
return offset
}
return 0
}
fileprivate func getTag(_ element: XMLHash.XMLElement) -> [String] {
let id = element.allAttributes["id"]?.text
return id.map { [$0] } ?? []
}
fileprivate func getOpacity(_ styleParts: [String: String]) -> Double {
if let opacityAttr = styleParts["opacity"] {
return getOpacity(opacityAttr)
}
return 1
}
fileprivate func getOpacity(_ opacity: String) -> Double {
return Double(opacity.replacingOccurrences(of: " ", with: "")) ?? 1
}
fileprivate func parseLine(_ line: XMLIndexer) -> Line? {
guard let element = line.element else {
return .none
}
return Line(x1: getDoubleValue(element, attribute: "x1") ?? 0,
y1: getDoubleValue(element, attribute: "y1") ?? 0,
x2: getDoubleValue(element, attribute: "x2") ?? 0,
y2: getDoubleValue(element, attribute: "y2") ?? 0)
}
fileprivate func parseRect(_ rect: XMLIndexer) -> Locus? {
guard let element = rect.element,
let width = getDoubleValue(element, attribute: "width"),
let height = getDoubleValue(element, attribute: "height"), width > 0 && height > 0 else {
return .none
}
let resultRect = Rect(x: getDoubleValue(element, attribute: "x") ?? 0,
y: getDoubleValue(element, attribute: "y") ?? 0,
w: width,
h: height)
let rxOpt = getDoubleValue(element, attribute: "rx")
let ryOpt = getDoubleValue(element, attribute: "ry")
if let rx = rxOpt, let ry = ryOpt {
return RoundRect(rect: resultRect, rx: rx, ry: ry)
}
let rOpt = rxOpt ?? ryOpt
if let r = rOpt, r >= 0 {
return RoundRect(rect: resultRect, rx: r, ry: r)
}
return resultRect
}
fileprivate func parseCircle(_ circle: XMLIndexer) -> Circle? {
guard let element = circle.element, let r = getDoubleValue(element, attribute: "r"), r > 0 else {
return .none
}
return Circle(cx: getDoubleValue(element, attribute: "cx") ?? 0,
cy: getDoubleValue(element, attribute: "cy") ?? 0,
r: r)
}
fileprivate func parseEllipse(_ ellipse: XMLIndexer) -> Arc? {
guard let element = ellipse.element,
let rx = getDoubleValue(element, attribute: "rx"),
let ry = getDoubleValue(element, attribute: "ry"), rx > 0 && ry > 0 else {
return .none
}
return Arc(
ellipse: Ellipse(cx: getDoubleValue(element, attribute: "cx") ?? 0,
cy: getDoubleValue(element, attribute: "cy") ?? 0,
rx: rx,
ry: ry),
shift: 0,
extent: degreesToRadians(360)
)
}
fileprivate func parsePolygon(_ polygon: XMLIndexer) -> Polygon? {
guard let element = polygon.element else {
return .none
}
if let points = element.allAttributes["points"]?.text {
return Polygon(points: parsePoints(points))
}
return .none
}
fileprivate func parsePolyline(_ polyline: XMLIndexer) -> Polyline? {
guard let element = polyline.element else {
return .none
}
if let points = element.allAttributes["points"]?.text {
return Polyline(points: parsePoints(points))
}
return .none
}