-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathSVGParser.java
More file actions
1617 lines (1481 loc) · 44.8 KB
/
SVGParser.java
File metadata and controls
1617 lines (1481 loc) · 44.8 KB
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
package com.larvalabs.svgandroid;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Picture;
import android.graphics.RadialGradient;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
import android.util.FloatMath;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE
* file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file
* to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
* applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/**
* @author Larva Labs, LLC
*/
public class SVGParser {
static final String TAG = "SVGAndroid";
private static boolean DISALLOW_DOCTYPE_DECL = true;
/**
* Parses a single SVG path and returns it as a <code>android.graphics.Path</code> object. An example path is
* <code>M250,150L150,350L350,350Z</code>, which draws a triangle.
*
* @param pathString the SVG path, see the specification <a href="http://www.w3.org/TR/SVG/paths.html">here</a>.
*/
public static Path parsePath(String pathString) {
return doPath(pathString);
}
static SVG parse(InputSource data, SVGHandler handler) throws SVGParseException {
try {
final Picture picture = new Picture();
handler.setPicture(picture);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(handler);
xr.setFeature("http://xml.org/sax/features/validation", false);
if (DISALLOW_DOCTYPE_DECL) {
try {
xr.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
} catch (SAXNotRecognizedException e) {
DISALLOW_DOCTYPE_DECL = false;
}
}
xr.parse(data);
SVG result = new SVG(picture, handler.bounds);
// Skip bounds if it was an empty pic
if (!Float.isInfinite(handler.limits.top)) {
result.setLimits(handler.limits);
}
return result;
} catch (Exception e) {
Log.e(TAG, "Failed to parse SVG.", e);
throw new SVGParseException(e);
}
}
private static NumberParse parseNumbers(String s) {
// Util.debug("Parsing numbers from: '" + s + "'");
int n = s.length();
int p = 0;
ArrayList<Float> numbers = new ArrayList<Float>();
boolean skipChar = false;
boolean prevWasE = false;
for (int i = 1; i < n; i++) {
if (skipChar) {
skipChar = false;
continue;
}
char c = s.charAt(i);
switch (c) {
// This ends the parsing, as we are on the next element
case 'M':
case 'm':
case 'Z':
case 'z':
case 'L':
case 'l':
case 'H':
case 'h':
case 'V':
case 'v':
case 'C':
case 'c':
case 'S':
case 's':
case 'Q':
case 'q':
case 'T':
case 't':
case 'a':
case 'A':
case ')': {
String str = s.substring(p, i);
if (str.trim().length() > 0) {
// Util.debug(" Last: " + str);
Float f = Float.parseFloat(str);
numbers.add(f);
}
p = i;
return new NumberParse(numbers, p);
}
case '-':
// Allow numbers with negative exp such as 7.23e-4
if (prevWasE) {
prevWasE = false;
break;
}
// fall-through
case '\n':
case '\t':
case ' ':
case ',': {
String str = s.substring(p, i);
// Just keep moving if multiple whitespace
if (str.trim().length() > 0) {
// Util.debug(" Next: " + str);
Float f = Float.parseFloat(str);
numbers.add(f);
if (c == '-') {
p = i;
} else {
p = i + 1;
skipChar = true;
}
} else {
p++;
}
prevWasE = false;
break;
}
case 'e':
prevWasE = true;
break;
default:
prevWasE = false;
}
}
String last = s.substring(p);
if (last.length() > 0) {
// Util.debug(" Last: " + last);
try {
numbers.add(Float.parseFloat(last));
} catch (NumberFormatException nfe) {
// Just white-space, forget it
}
p = s.length();
}
return new NumberParse(numbers, p);
}
private static final Pattern TRANSFORM_SEP = Pattern.compile("[\\s,]*");
/**
* Parse a list of transforms such as: foo(n,n,n...) bar(n,n,n..._ ...) Delimiters are whitespaces or commas
*/
private static Matrix parseTransform(String s) {
Matrix matrix = new Matrix();
while (true) {
parseTransformItem(s, matrix);
// Log.i(TAG, "Transformed: (" + s + ") " + matrix);
final int rparen = s.indexOf(")");
if (rparen > 0 && s.length() > rparen + 1) {
s = TRANSFORM_SEP.matcher(s.substring(rparen + 1)).replaceFirst("");
} else {
break;
}
}
return matrix;
}
private static Matrix parseTransformItem(String s, Matrix matrix) {
if (s.startsWith("matrix(")) {
NumberParse np = parseNumbers(s.substring("matrix(".length()));
if (np.numbers.size() == 6) {
Matrix mat = new Matrix();
mat.setValues(new float[] {
// Row 1
np.numbers.get(0), np.numbers.get(2), np.numbers.get(4),
// Row 2
np.numbers.get(1), np.numbers.get(3), np.numbers.get(5),
// Row 3
0, 0, 1, });
matrix.preConcat(mat);
}
} else if (s.startsWith("translate(")) {
NumberParse np = parseNumbers(s.substring("translate(".length()));
if (np.numbers.size() > 0) {
float tx = np.numbers.get(0);
float ty = 0;
if (np.numbers.size() > 1) {
ty = np.numbers.get(1);
}
matrix.preTranslate(tx, ty);
}
} else if (s.startsWith("scale(")) {
NumberParse np = parseNumbers(s.substring("scale(".length()));
if (np.numbers.size() > 0) {
float sx = np.numbers.get(0);
float sy = sx;
if (np.numbers.size() > 1) {
sy = np.numbers.get(1);
}
matrix.preScale(sx, sy);
}
} else if (s.startsWith("skewX(")) {
NumberParse np = parseNumbers(s.substring("skewX(".length()));
if (np.numbers.size() > 0) {
float angle = np.numbers.get(0);
matrix.preSkew((float) Math.tan(angle), 0);
}
} else if (s.startsWith("skewY(")) {
NumberParse np = parseNumbers(s.substring("skewY(".length()));
if (np.numbers.size() > 0) {
float angle = np.numbers.get(0);
matrix.preSkew(0, (float) Math.tan(angle));
}
} else if (s.startsWith("rotate(")) {
NumberParse np = parseNumbers(s.substring("rotate(".length()));
if (np.numbers.size() > 0) {
float angle = np.numbers.get(0);
float cx = 0;
float cy = 0;
if (np.numbers.size() > 2) {
cx = np.numbers.get(1);
cy = np.numbers.get(2);
}
matrix.preTranslate(-cx, -cy);
matrix.preRotate(angle);
matrix.preTranslate(cx, cy);
}
} else {
Log.w(TAG, "Invalid transform (" + s + ")");
}
return matrix;
}
/**
* This is where the hard-to-parse paths are handled. Uppercase rules are absolute positions, lowercase are
* relative. Types of path rules:
* <p/>
* <ol>
* <li>M/m - (x y)+ - Move to (without drawing)
* <li>Z/z - (no params) - Close path (back to starting point)
* <li>L/l - (x y)+ - Line to
* <li>H/h - x+ - Horizontal ine to
* <li>V/v - y+ - Vertical line to
* <li>C/c - (x1 y1 x2 y2 x y)+ - Cubic bezier to
* <li>S/s - (x2 y2 x y)+ - Smooth cubic bezier to (shorthand that assumes the x2, y2 from previous C/S is the x1,
* y1 of this bezier)
* <li>Q/q - (x1 y1 x y)+ - Quadratic bezier to
* <li>T/t - (x y)+ - Smooth quadratic bezier to (assumes previous control point is "reflection" of last one w.r.t.
* to current point)
* </ol>
* <p/>
* Numbers are separate by whitespace, comma or nothing at all (!) if they are self-delimiting, (ie. begin with a -
* sign)
*
* @param s the path string from the XML
*/
private static Path doPath(String s) {
int n = s.length();
ParserHelper ph = new ParserHelper(s, 0);
ph.skipWhitespace();
Path p = new Path();
float lastX = 0;
float lastY = 0;
float lastX1 = 0;
float lastY1 = 0;
float subPathStartX = 0;
float subPathStartY = 0;
char prevCmd = 0;
while (ph.pos < n) {
char cmd = s.charAt(ph.pos);
switch (cmd) {
case '-':
case '+':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (prevCmd == 'm' || prevCmd == 'M') {
cmd = (char) ((prevCmd) - 1);
break;
} else if (("lhvcsqta").indexOf(Character.toLowerCase(prevCmd)) >= 0) {
cmd = prevCmd;
break;
}
default: {
ph.advance();
prevCmd = cmd;
}
}
boolean wasCurve = false;
switch (cmd) {
case 'M':
case 'm': {
float x = ph.nextFloat();
float y = ph.nextFloat();
if (cmd == 'm') {
subPathStartX += x;
subPathStartY += y;
p.rMoveTo(x, y);
lastX += x;
lastY += y;
} else {
subPathStartX = x;
subPathStartY = y;
p.moveTo(x, y);
lastX = x;
lastY = y;
}
break;
}
case 'Z':
case 'z': {
p.close();
p.moveTo(subPathStartX, subPathStartY);
lastX = subPathStartX;
lastY = subPathStartY;
lastX1 = subPathStartX;
lastY1 = subPathStartY;
wasCurve = true;
break;
}
case 'T':
case 't':
// todo - smooth quadratic Bezier (two parameters)
case 'L':
case 'l': {
float x = ph.nextFloat();
float y = ph.nextFloat();
if (cmd == 'l') {
p.rLineTo(x, y);
lastX += x;
lastY += y;
} else {
p.lineTo(x, y);
lastX = x;
lastY = y;
}
break;
}
case 'H':
case 'h': {
float x = ph.nextFloat();
if (cmd == 'h') {
p.rLineTo(x, 0);
lastX += x;
} else {
p.lineTo(x, lastY);
lastX = x;
}
break;
}
case 'V':
case 'v': {
float y = ph.nextFloat();
if (cmd == 'v') {
p.rLineTo(0, y);
lastY += y;
} else {
p.lineTo(lastX, y);
lastY = y;
}
break;
}
case 'C':
case 'c': {
wasCurve = true;
float x1 = ph.nextFloat();
float y1 = ph.nextFloat();
float x2 = ph.nextFloat();
float y2 = ph.nextFloat();
float x = ph.nextFloat();
float y = ph.nextFloat();
if (cmd == 'c') {
x1 += lastX;
x2 += lastX;
x += lastX;
y1 += lastY;
y2 += lastY;
y += lastY;
}
p.cubicTo(x1, y1, x2, y2, x, y);
lastX1 = x2;
lastY1 = y2;
lastX = x;
lastY = y;
break;
}
case 'Q':
case 'q':
// todo - quadratic Bezier (four parameters)
case 'S':
case 's': {
wasCurve = true;
float x2 = ph.nextFloat();
float y2 = ph.nextFloat();
float x = ph.nextFloat();
float y = ph.nextFloat();
if (Character.isLowerCase(cmd)) {
x2 += lastX;
x += lastX;
y2 += lastY;
y += lastY;
}
float x1 = 2 * lastX - lastX1;
float y1 = 2 * lastY - lastY1;
p.cubicTo(x1, y1, x2, y2, x, y);
lastX1 = x2;
lastY1 = y2;
lastX = x;
lastY = y;
break;
}
case 'A':
case 'a': {
float rx = ph.nextFloat();
float ry = ph.nextFloat();
float theta = ph.nextFloat();
int largeArc = ph.nextFlag();
int sweepArc = ph.nextFlag();
float x = ph.nextFloat();
float y = ph.nextFloat();
if (cmd == 'a') {
x += lastX;
y += lastY;
}
drawArc(p, lastX, lastY, x, y, rx, ry, theta, largeArc, sweepArc);
lastX = x;
lastY = y;
break;
}
default:
Log.w(TAG, "Invalid path command: " + cmd);
ph.advance();
}
if (!wasCurve) {
lastX1 = lastX;
lastY1 = lastY;
}
ph.skipWhitespace();
}
return p;
}
private static float angle(float x1, float y1, float x2, float y2) {
return (float) Math.toDegrees(Math.atan2(x1, y1) - Math.atan2(x2, y2)) % 360;
}
private static final RectF arcRectf = new RectF();
private static final Matrix arcMatrix = new Matrix();
private static final Matrix arcMatrix2 = new Matrix();
private static void drawArc(Path p, float lastX, float lastY, float x, float y, float rx, float ry, float theta,
int largeArc, int sweepArc) {
// Log.d("drawArc", "from (" + lastX + "," + lastY + ") to (" + x + ","+ y + ") r=(" + rx + "," + ry +
// ") theta=" + theta + " flags="+ largeArc + "," + sweepArc);
// http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
if (rx == 0 || ry == 0) {
p.lineTo(x, y);
return;
}
if (x == lastX && y == lastY) {
return; // nothing to draw
}
rx = Math.abs(rx);
ry = Math.abs(ry);
final float thrad = theta * (float) Math.PI / 180;
final float st = FloatMath.sin(thrad);
final float ct = FloatMath.cos(thrad);
final float xc = (lastX - x) / 2;
final float yc = (lastY - y) / 2;
final float x1t = ct * xc + st * yc;
final float y1t = -st * xc + ct * yc;
final float x1ts = x1t * x1t;
final float y1ts = y1t * y1t;
float rxs = rx * rx;
float rys = ry * ry;
float lambda = (x1ts / rxs + y1ts / rys) * 1.001f; // add 0.1% to be sure that no out of range occurs due to
// limited precision
if (lambda > 1) {
float lambdasr = FloatMath.sqrt(lambda);
rx *= lambdasr;
ry *= lambdasr;
rxs = rx * rx;
rys = ry * ry;
}
final float R =
FloatMath.sqrt((rxs * rys - rxs * y1ts - rys * x1ts) / (rxs * y1ts + rys * x1ts))
* ((largeArc == sweepArc) ? -1 : 1);
final float cxt = R * rx * y1t / ry;
final float cyt = -R * ry * x1t / rx;
final float cx = ct * cxt - st * cyt + (lastX + x) / 2;
final float cy = st * cxt + ct * cyt + (lastY + y) / 2;
final float th1 = angle(1, 0, (x1t - cxt) / rx, (y1t - cyt) / ry);
float dth = angle((x1t - cxt) / rx, (y1t - cyt) / ry, (-x1t - cxt) / rx, (-y1t - cyt) / ry);
if (sweepArc == 0 && dth > 0) {
dth -= 360;
} else if (sweepArc != 0 && dth < 0) {
dth += 360;
}
// draw
if ((theta % 360) == 0) {
// no rotate and translate need
arcRectf.set(cx - rx, cy - ry, cx + rx, cy + ry);
p.arcTo(arcRectf, th1, dth);
} else {
// this is the hard and slow part :-)
arcRectf.set(-rx, -ry, rx, ry);
arcMatrix.reset();
arcMatrix.postRotate(theta);
arcMatrix.postTranslate(cx, cy);
arcMatrix.invert(arcMatrix2);
p.transform(arcMatrix2);
p.arcTo(arcRectf, th1, dth);
p.transform(arcMatrix);
}
}
private static NumberParse getNumberParseAttr(String name, Attributes attributes) {
int n = attributes.getLength();
for (int i = 0; i < n; i++) {
if (attributes.getLocalName(i).equals(name)) {
return parseNumbers(attributes.getValue(i));
}
}
return null;
}
private static String getStringAttr(String name, Attributes attributes) {
int n = attributes.getLength();
for (int i = 0; i < n; i++) {
if (attributes.getLocalName(i).equals(name)) {
return attributes.getValue(i);
}
}
return null;
}
private static Float getFloatAttr(String name, Attributes attributes) {
return getFloatAttr(name, attributes, null);
}
private static Float getFloatAttr(String name, Attributes attributes, Float defaultValue) {
String v = getStringAttr(name, attributes);
return parseFloatValue(v, defaultValue);
}
private static float getFloatAttr(String name, Attributes attributes, float defaultValue) {
String v = getStringAttr(name, attributes);
return parseFloatValue(v, defaultValue);
}
private static Float parseFloatValue(String str, Float defaultValue) {
if (str == null) {
return defaultValue;
} else if (str.endsWith("px")) {
str = str.substring(0, str.length() - 2);
} else if (str.endsWith("%")) {
str = str.substring(0, str.length() - 1);
return Float.parseFloat(str) / 100;
}
// Log.d(TAG, "Float parsing '" + name + "=" + v + "'");
return Float.parseFloat(str);
}
private static class NumberParse {
private ArrayList<Float> numbers;
private int nextCmd;
public NumberParse(ArrayList<Float> numbers, int nextCmd) {
this.numbers = numbers;
this.nextCmd = nextCmd;
}
public int getNextCmd() {
return nextCmd;
}
public float getNumber(int index) {
return numbers.get(index);
}
}
private static class Gradient {
String id;
String xlink;
boolean isLinear;
float x1, y1, x2, y2;
float x, y, radius;
ArrayList<Float> positions = new ArrayList<Float>();
ArrayList<Integer> colors = new ArrayList<Integer>();
Matrix matrix = null;
public Shader shader = null;
public boolean boundingBox = false;
public TileMode tilemode;
/*
public Gradient createChild(Gradient g) {
Gradient child = new Gradient();
child.id = g.id;
child.xlink = id;
child.isLinear = g.isLinear;
child.x1 = g.x1;
child.x2 = g.x2;
child.y1 = g.y1;
child.y2 = g.y2;
child.x = g.x;
child.y = g.y;
child.radius = g.radius;
child.positions = positions;
child.colors = colors;
child.matrix = matrix;
if (g.matrix != null) {
if (matrix == null) {
child.matrix = g.matrix;
} else {
Matrix m = new Matrix(matrix);
m.preConcat(g.matrix);
child.matrix = m;
}
}
child.boundingBox = g.boundingBox;
child.shader = g.shader;
child.tilemode = g.tilemode;
return child;
}
*/
public void inherit(Gradient parent) {
Gradient child = this;
child.xlink = parent.id;
child.positions = parent.positions;
child.colors = parent.colors;
if (child.matrix == null) {
child.matrix = parent.matrix;
} else if (parent.matrix != null) {
Matrix m = new Matrix(parent.matrix);
m.preConcat(child.matrix);
child.matrix = m;
}
}
}
private static class StyleSet {
HashMap<String, String> styleMap = new HashMap<String, String>();
private StyleSet(String string) {
String[] styles = string.split(";");
for (String s : styles) {
String[] style = s.split(":");
if (style.length == 2) {
styleMap.put(style[0], style[1]);
}
}
}
public String getStyle(String name) {
return styleMap.get(name);
}
}
private static class Properties {
StyleSet styles = null;
Attributes atts;
private Properties(Attributes atts) {
this.atts = atts;
String styleAttr = getStringAttr("style", atts);
if (styleAttr != null) {
styles = new StyleSet(styleAttr);
}
}
public String getAttr(String name) {
String v = null;
if (styles != null) {
v = styles.getStyle(name);
}
if (v == null) {
v = getStringAttr(name, atts);
}
return v;
}
public String getString(String name) {
return getAttr(name);
}
private Integer rgb(int r, int g, int b) {
return ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff);
}
private int parseNum(String v) throws NumberFormatException {
if (v.endsWith("%")) {
v = v.substring(0, v.length() - 1);
return Math.round(Float.parseFloat(v) / 100 * 255);
}
return Integer.parseInt(v);
}
public Integer getColor(String name) {
String v = name;
if (v == null) {
return null;
} else if (v.startsWith("#")) {
try { // #RRGGBB or #AARRGGBB
return Color.parseColor(v);
} catch (IllegalArgumentException iae) {
return null;
}
} else if (v.startsWith("rgb(") && v.endsWith(")")) {
String values[] = v.substring(4, v.length() - 1).split(",");
try {
return rgb(parseNum(values[0]), parseNum(values[1]), parseNum(values[2]));
} catch (NumberFormatException nfe) {
return null;
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
} else {
return SVGColors.mapColour(v);
}
}
// convert 0xRGB into 0xRRGGBB
private int hex3Tohex6(int x) {
return (x & 0xF00) << 8 | (x & 0xF00) << 12 | (x & 0xF0) << 4 | (x & 0xF0) << 8 | (x & 0xF) << 4
| (x & 0xF);
}
public float getFloat(String name, float defaultValue) {
String v = getAttr(name);
if (v == null) {
return defaultValue;
} else {
try {
return Float.parseFloat(v);
} catch (NumberFormatException nfe) {
return defaultValue;
}
}
}
public Float getFloat(String name, Float defaultValue) {
String v = getAttr(name);
if (v == null) {
return defaultValue;
} else {
try {
return Float.parseFloat(v);
} catch (NumberFormatException nfe) {
return defaultValue;
}
}
}
public Float getFloat(String name) {
return getFloat(name, null);
}
}
private static class LayerAttributes {
public final float opacity;
public LayerAttributes(float opacity) {
this.opacity = opacity;
}
}
static class SVGHandler extends DefaultHandler {
private Picture picture;
private Canvas canvas;
private Float limitsAdjustmentX, limitsAdjustmentY;
final LinkedList<LayerAttributes> layerAttributeStack = new LinkedList<LayerAttributes>();
Paint strokePaint;
boolean strokeSet = false;
final LinkedList<Paint> strokePaintStack = new LinkedList<Paint>();
final LinkedList<Boolean> strokeSetStack = new LinkedList<Boolean>();
Paint fillPaint;
boolean fillSet = false;
final LinkedList<Paint> fillPaintStack = new LinkedList<Paint>();
final LinkedList<Boolean> fillSetStack = new LinkedList<Boolean>();
Paint textPaint;
boolean drawCharacters;
// See http://stackoverflow.com/questions/4567636/java-sax-parser-split-calls-to-characters
StringBuilder textBuilder;
Float textX;
Float textY;
int newLineCount;
Float textSize;
Matrix font_matrix;
// Scratch rect (so we aren't constantly making new ones)
final RectF rect = new RectF();
RectF bounds = null;
final RectF limits = new RectF(
Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY);
Integer searchColor = null;
Integer replaceColor = null;
Float opacityMultiplier = null;
boolean whiteMode = false;
Integer canvasRestoreCount;
final LinkedList<Boolean> transformStack = new LinkedList<Boolean>();
final LinkedList<Matrix> matrixStack = new LinkedList<Matrix>();
final HashMap<String, Gradient> gradientMap = new HashMap<String, Gradient>();
Gradient gradient = null;
public SVGHandler() {
strokePaint = new Paint();
strokePaint.setAntiAlias(true);
strokePaint.setStyle(Paint.Style.STROKE);
fillPaint = new Paint();
fillPaint.setAntiAlias(true);
fillPaint.setStyle(Paint.Style.FILL);
textPaint = new Paint();
textPaint.setAntiAlias(true);
matrixStack.addFirst(new Matrix());
layerAttributeStack.addFirst(new LayerAttributes(1f));
}
void setPicture(Picture picture) {
this.picture = picture;
}
public void setColorSwap(Integer searchColor, Integer replaceColor, boolean overideOpacity) {
this.searchColor = searchColor;
this.replaceColor = replaceColor;
if (replaceColor != null && overideOpacity) {
opacityMultiplier = ((replaceColor >> 24) & 0x000000FF) / 255f;
} else {
opacityMultiplier = null;
}
}
public void setWhiteMode(boolean whiteMode) {
this.whiteMode = whiteMode;
}
@Override
public void startDocument() throws SAXException {
// Set up prior to parsing a doc
}
@Override
public void endDocument() throws SAXException {
// Clean up after parsing a doc
}
private final Matrix gradMatrix = new Matrix();
private boolean doFill(Properties atts, RectF bounding_box) {
if ("none".equals(atts.getString("display"))) {
return false;
}
if (whiteMode) {
fillPaint.setShader(null);
fillPaint.setColor(Color.WHITE);
return true;
}
String fillString = atts.getString("fill");
if (fillString == null && SVG_FILL != null) {
fillString = SVG_FILL;
}
if (fillString != null) {
if (fillString.startsWith("url(#")) {
// It's a gradient fill, look it up in our map
String id = fillString.substring("url(#".length(), fillString.length() - 1);
Gradient g = gradientMap.get(id);
Shader shader = null;
if (g != null) {
shader = g.shader;
}
if (shader != null) {
// Util.debug("Found shader!");
fillPaint.setShader(shader);
gradMatrix.set(g.matrix);
if (g.boundingBox && bounding_box != null) {
// Log.d("svg", "gradient is bounding box");
gradMatrix.preTranslate(bounding_box.left, bounding_box.top);
gradMatrix.preScale(bounding_box.width(), bounding_box.height());
}
shader.setLocalMatrix(gradMatrix);
return true;
} else {
Log.w(TAG, "Didn't find shader, using black: " + id);
fillPaint.setShader(null);
doColor(atts, Color.BLACK, true, fillPaint);
return true;
}
} else if (fillString.equalsIgnoreCase("none")) {
fillPaint.setShader(null);
fillPaint.setColor(Color.TRANSPARENT);
return true;
} else {
fillPaint.setShader(null);
Integer color = atts.getColor(fillString);
if (color != null) {
doColor(atts, color, true, fillPaint);
return true;
} else {
Log.w(TAG, "Unrecognized fill color, using black: " + fillString);
doColor(atts, Color.BLACK, true, fillPaint);
return true;
}
}
} else {
if (fillSet) {
// If fill is set, inherit from parent
return fillPaint.getColor() != Color.TRANSPARENT; // optimization
} else {
// Default is black fill
fillPaint.setShader(null);
fillPaint.setColor(Color.BLACK);
return true;
}
}
}
private boolean doStroke(Properties atts) {
if (whiteMode) {
// Never stroke in white mode
return false;
}
if ("none".equals(atts.getString("display"))) {
return false;
}