Fix SVACE issue
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / third-party / nanosvg / nanosvg.cc
1 /*
2  * Copyright (c) 2013-14 Mikko Mononen memon@inside.org
3  *
4  * This software is provided 'as-is', without any express or implied
5  * warranty.  In no event will the authors be held liable for any damages
6  * arising from the use of this software.
7  *
8  * Permission is granted to anyone to use this software for any purpose,
9  * including commercial applications, and to alter it and redistribute it
10  * freely, subject to the following restrictions:
11  *
12  * 1. The origin of this software must not be misrepresented; you must not
13  * claim that you wrote the original software. If you use this software
14  * in a product, an acknowledgment in the product documentation would be
15  * appreciated but is not required.
16  * 2. Altered source versions must be plainly marked as such, and must not be
17  * misrepresented as being the original software.
18  * 3. This notice may not be removed or altered from any source distribution.
19  *
20  * The SVG parser is based on Anti-Grain Geometry 2.4 SVG example
21  * Copyright (C) 2002-2004 Maxim Shemanarev (McSeem) (http://www.antigrain.com/)
22  *
23  * Arc calculation code based on canvg (https://code.google.com/p/canvg/)
24  *
25  * Bounding box calculation based on http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
26  *
27  */
28
29 #include "nanosvg.h"
30
31 /**
32  * In the original software, The nanosvg implementation was included in the header file.
33  * We have separated the implementation to source file here.
34  */
35
36 #include <stdio.h>
37 #include <string.h>
38 #include <stdlib.h>
39 #include <math.h>
40
41 #define NSVG_PI (3.14159265358979323846264338327f)
42 #define NSVG_KAPPA90 (0.5522847493f)    // Lenght proportional to radius of a cubic bezier handle for 90deg arcs.
43
44 #define NSVG_ALIGN_MIN 0
45 #define NSVG_ALIGN_MID 1
46 #define NSVG_ALIGN_MAX 2
47 #define NSVG_ALIGN_NONE 0
48 #define NSVG_ALIGN_MEET 1
49 #define NSVG_ALIGN_SLICE 2
50
51 #define NSVG_NOTUSED(v) do { (void)(1 ? (void)0 : ( (void)(v) ) ); } while(0)
52 #define NSVG_RGB(r, g, b) (((unsigned int)r) | ((unsigned int)g << 8) | ((unsigned int)b << 16))
53
54 #define NSVG_INLINE inline
55
56
57 static int nsvg__isspace(char c)
58 {
59         return strchr(" \t\n\v\f\r", c) != 0;
60 }
61
62 static int nsvg__isdigit(char c)
63 {
64         return c >= '0' && c <= '9';
65 }
66
67 static int nsvg__isnum(char c)
68 {
69         return strchr("0123456789+-.eE", c) != 0;
70 }
71
72 static NSVG_INLINE float nsvg__minf(float a, float b) { return a < b ? a : b; }
73 static NSVG_INLINE float nsvg__maxf(float a, float b) { return a > b ? a : b; }
74
75
76 // Simple XML parser
77
78 #define NSVG_XML_TAG 1
79 #define NSVG_XML_CONTENT 2
80 #define NSVG_XML_MAX_ATTRIBS 256
81
82 static void nsvg__parseContent(char* s,
83                                                            void (*contentCb)(void* ud, const char* s),
84                                                            void* ud)
85 {
86         // Trim start white spaces
87         while (*s && nsvg__isspace(*s)) s++;
88         if (!*s) return;
89
90         if (contentCb)
91                 (*contentCb)(ud, s);
92 }
93
94 static void nsvg__parseElement(char* s,
95                                                            void (*startelCb)(void* ud, const char* el, const char** attr),
96                                                            void (*endelCb)(void* ud, const char* el),
97                                                            void* ud)
98 {
99         const char* attr[NSVG_XML_MAX_ATTRIBS];
100         int nattr = 0;
101         char* name;
102         int start = 0;
103         int end = 0;
104         char quote;
105
106         /**
107          * In the original file, 's' is not compared to NULL value before it is dereferenced.
108          */
109         if (!s)
110         {
111                 return;
112         }
113
114         // Skip white space after the '<'
115         while (*s && nsvg__isspace(*s)) s++;
116
117         // Check if the tag is end tag
118         if (*s == '/') {
119                 s++;
120                 end = 1;
121         } else {
122                 start = 1;
123         }
124
125         // Skip comments, data and preprocessor stuff.
126         if (!*s || *s == '?' || *s == '!')
127                 return;
128
129         // Get tag name
130         name = s;
131         while (*s && !nsvg__isspace(*s)) s++;
132         if (*s) { *s++ = '\0'; }
133
134         // Get attribs
135         while (!end && *s && nattr < NSVG_XML_MAX_ATTRIBS-3) {
136                 char* name = NULL;
137                 char* value = NULL;
138
139                 // Skip white space before the attrib name
140                 while (*s && nsvg__isspace(*s)) s++;
141                 if (!*s) break;
142                 if (*s == '/') {
143                         end = 1;
144                         break;
145                 }
146                 name = s;
147                 // Find end of the attrib name.
148                 while (*s && !nsvg__isspace(*s) && *s != '=') s++;
149                 if (*s) { *s++ = '\0'; }
150                 // Skip until the beginning of the value.
151                 while (*s && *s != '\"' && *s != '\'') s++;
152                 if (!*s) break;
153                 quote = *s;
154                 s++;
155                 // Store value and find the end of it.
156                 value = s;
157                 while (*s && *s != quote) s++;
158                 if (*s) { *s++ = '\0'; }
159
160                 // Store only well formed attributes
161                 if (name && value) {
162                         attr[nattr++] = name;
163                         attr[nattr++] = value;
164                 }
165         }
166
167         // List terminator
168         attr[nattr++] = 0;
169         attr[nattr++] = 0;
170
171         // Call callbacks.
172         if (start && startelCb)
173                 (*startelCb)(ud, name, attr);
174         if (end && endelCb)
175                 (*endelCb)(ud, name);
176 }
177
178 int nsvg__parseXML(char* input,
179                                    void (*startelCb)(void* ud, const char* el, const char** attr),
180                                    void (*endelCb)(void* ud, const char* el),
181                                    void (*contentCb)(void* ud, const char* s),
182                                    void* ud)
183 {
184         char* s = input;
185         char* mark = s;
186         int state = NSVG_XML_CONTENT;
187         while (*s) {
188                 if (*s == '<' && state == NSVG_XML_CONTENT) {
189                         // Start of a tag
190                         *s++ = '\0';
191                         nsvg__parseContent(mark, contentCb, ud);
192                         mark = s;
193                         state = NSVG_XML_TAG;
194                 } else if (*s == '>' && state == NSVG_XML_TAG) {
195                         // Start of a content or new tag.
196                         *s++ = '\0';
197                         nsvg__parseElement(mark, startelCb, endelCb, ud);
198                         mark = s;
199                         state = NSVG_XML_CONTENT;
200                 } else {
201                         s++;
202                 }
203         }
204
205         return 1;
206 }
207
208
209 /* Simple SVG parser. */
210
211 #define NSVG_MAX_ATTR 128
212
213 enum NSVGgradientUnits {
214         NSVG_USER_SPACE = 0,
215         NSVG_OBJECT_SPACE = 1
216 };
217
218 #define NSVG_MAX_DASHES 8
219
220 enum NSVGunits {
221         NSVG_UNITS_USER,
222         NSVG_UNITS_PX,
223         NSVG_UNITS_PT,
224         NSVG_UNITS_PC,
225         NSVG_UNITS_MM,
226         NSVG_UNITS_CM,
227         NSVG_UNITS_IN,
228         NSVG_UNITS_PERCENT,
229         NSVG_UNITS_EM,
230         NSVG_UNITS_EX
231 };
232
233 typedef struct NSVGcoordinate {
234         float value;
235         int units;
236 } NSVGcoordinate;
237
238 typedef struct NSVGlinearData {
239         NSVGcoordinate x1, y1, x2, y2;
240 } NSVGlinearData;
241
242 typedef struct NSVGradialData {
243         NSVGcoordinate cx, cy, r, fx, fy;
244 } NSVGradialData;
245
246 typedef struct NSVGgradientData
247 {
248         char id[64];
249         char ref[64];
250   /**
251    * In the original file, using char type (without signed or unsigned) can be interpreted
252    * as 'unsigned char' in some build environments, like ARM architecture.
253    * To prevent the unexpected behavior, we replace 'char type' with 'signed char type' here.
254    */
255     signed char type;
256         union {
257                 NSVGlinearData linear;
258                 NSVGradialData radial;
259         };
260         char spread;
261         /**
262          * In the original file, using char type (without signed or unsigned) can be interpreted
263          * as 'unsigned char' in some build environments, like ARM architecture.
264          * To prevent the unexpected behavior, we replace 'char units' with 'signed char units' here.
265          */
266     signed char units;
267         float xform[6];
268         int nstops;
269         NSVGgradientStop* stops;
270         struct NSVGgradientData* next;
271 } NSVGgradientData;
272
273 typedef struct NSVGattrib
274 {
275         char id[64];
276         float xform[6];
277         unsigned int fillColor;
278         unsigned int strokeColor;
279         float opacity;
280         float fillOpacity;
281         float strokeOpacity;
282         char fillGradient[64];
283         char strokeGradient[64];
284         float strokeWidth;
285         float strokeDashOffset;
286         float strokeDashArray[NSVG_MAX_DASHES];
287         int strokeDashCount;
288         char strokeLineJoin;
289         char strokeLineCap;
290         float miterLimit;
291         char fillRule;
292         float fontSize;
293         unsigned int stopColor;
294         float stopOpacity;
295         float stopOffset;
296         char hasFill;
297         char hasStroke;
298         char visible;
299 } NSVGattrib;
300
301 typedef struct NSVGparser
302 {
303         NSVGattrib attr[NSVG_MAX_ATTR];
304         int attrHead;
305         float* pts;
306         int npts;
307         int cpts;
308         NSVGpath* plist;
309         NSVGimage* image;
310         NSVGgradientData* gradients;
311         NSVGshape* shapesTail;
312         float viewMinx, viewMiny, viewWidth, viewHeight;
313         int alignX, alignY, alignType;
314         float dpi;
315         char pathFlag;
316         char defsFlag;
317 } NSVGparser;
318
319 static void nsvg__xformIdentity(float* t)
320 {
321         t[0] = 1.0f; t[1] = 0.0f;
322         t[2] = 0.0f; t[3] = 1.0f;
323         t[4] = 0.0f; t[5] = 0.0f;
324 }
325
326 static void nsvg__xformSetTranslation(float* t, float tx, float ty)
327 {
328         t[0] = 1.0f; t[1] = 0.0f;
329         t[2] = 0.0f; t[3] = 1.0f;
330         t[4] = tx; t[5] = ty;
331 }
332
333 static void nsvg__xformSetScale(float* t, float sx, float sy)
334 {
335         t[0] = sx; t[1] = 0.0f;
336         t[2] = 0.0f; t[3] = sy;
337         t[4] = 0.0f; t[5] = 0.0f;
338 }
339
340 static void nsvg__xformSetSkewX(float* t, float a)
341 {
342         t[0] = 1.0f; t[1] = 0.0f;
343         t[2] = tanf(a); t[3] = 1.0f;
344         t[4] = 0.0f; t[5] = 0.0f;
345 }
346
347 static void nsvg__xformSetSkewY(float* t, float a)
348 {
349         t[0] = 1.0f; t[1] = tanf(a);
350         t[2] = 0.0f; t[3] = 1.0f;
351         t[4] = 0.0f; t[5] = 0.0f;
352 }
353
354 static void nsvg__xformSetRotation(float* t, float a)
355 {
356         float cs = cosf(a), sn = sinf(a);
357         t[0] = cs; t[1] = sn;
358         t[2] = -sn; t[3] = cs;
359         t[4] = 0.0f; t[5] = 0.0f;
360 }
361
362 static void nsvg__xformMultiply(float* t, float* s)
363 {
364         float t0 = t[0] * s[0] + t[1] * s[2];
365         float t2 = t[2] * s[0] + t[3] * s[2];
366         float t4 = t[4] * s[0] + t[5] * s[2] + s[4];
367         t[1] = t[0] * s[1] + t[1] * s[3];
368         t[3] = t[2] * s[1] + t[3] * s[3];
369         t[5] = t[4] * s[1] + t[5] * s[3] + s[5];
370         t[0] = t0;
371         t[2] = t2;
372         t[4] = t4;
373 }
374
375 static void nsvg__xformInverse(float* inv, float* t)
376 {
377         double invdet, det = (double)t[0] * t[3] - (double)t[2] * t[1];
378         if (det > -1e-6 && det < 1e-6) {
379                 nsvg__xformIdentity(t);
380                 return;
381         }
382         invdet = 1.0 / det;
383         inv[0] = (float)(t[3] * invdet);
384         inv[2] = (float)(-t[2] * invdet);
385         inv[4] = (float)(((double)t[2] * t[5] - (double)t[3] * t[4]) * invdet);
386         inv[1] = (float)(-t[1] * invdet);
387         inv[3] = (float)(t[0] * invdet);
388         inv[5] = (float)(((double)t[1] * t[4] - (double)t[0] * t[5]) * invdet);
389 }
390
391 static void nsvg__xformPremultiply(float* t, float* s)
392 {
393         float s2[6];
394         memcpy(s2, s, sizeof(float)*6);
395         nsvg__xformMultiply(s2, t);
396         memcpy(t, s2, sizeof(float)*6);
397 }
398
399 static void nsvg__xformPoint(float* dx, float* dy, float x, float y, float* t)
400 {
401         *dx = x*t[0] + y*t[2] + t[4];
402         *dy = x*t[1] + y*t[3] + t[5];
403 }
404
405 static void nsvg__xformVec(float* dx, float* dy, float x, float y, float* t)
406 {
407         *dx = x*t[0] + y*t[2];
408         *dy = x*t[1] + y*t[3];
409 }
410
411 #define NSVG_EPSILON (1e-12)
412
413 static int nsvg__ptInBounds(float* pt, float* bounds)
414 {
415         return pt[0] >= bounds[0] && pt[0] <= bounds[2] && pt[1] >= bounds[1] && pt[1] <= bounds[3];
416 }
417
418
419 static double nsvg__evalBezier(double t, double p0, double p1, double p2, double p3)
420 {
421         double it = 1.0-t;
422         return it*it*it*p0 + 3.0*it*it*t*p1 + 3.0*it*t*t*p2 + t*t*t*p3;
423 }
424
425 static void nsvg__curveBounds(float* bounds, float* curve)
426 {
427         int i, j, count;
428         double roots[2], a, b, c, b2ac, t, v;
429         float* v0 = &curve[0];
430         float* v1 = &curve[2];
431         float* v2 = &curve[4];
432         float* v3 = &curve[6];
433
434         // Start the bounding box by end points
435         bounds[0] = nsvg__minf(v0[0], v3[0]);
436         bounds[1] = nsvg__minf(v0[1], v3[1]);
437         bounds[2] = nsvg__maxf(v0[0], v3[0]);
438         bounds[3] = nsvg__maxf(v0[1], v3[1]);
439
440         // Bezier curve fits inside the convex hull of it's control points.
441         // If control points are inside the bounds, we're done.
442         if (nsvg__ptInBounds(v1, bounds) && nsvg__ptInBounds(v2, bounds))
443                 return;
444
445         // Add bezier curve inflection points in X and Y.
446         for (i = 0; i < 2; i++) {
447                 a = -3.0 * v0[i] + 9.0 * v1[i] - 9.0 * v2[i] + 3.0 * v3[i];
448                 b = 6.0 * v0[i] - 12.0 * v1[i] + 6.0 * v2[i];
449                 c = 3.0 * v1[i] - 3.0 * v0[i];
450                 count = 0;
451                 if (fabs(a) < NSVG_EPSILON) {
452                         if (fabs(b) > NSVG_EPSILON) {
453                                 t = -c / b;
454                                 if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON)
455                                         roots[count++] = t;
456                         }
457                 } else {
458                         b2ac = b*b - 4.0*c*a;
459                         if (b2ac > NSVG_EPSILON) {
460                                 t = (-b + sqrt(b2ac)) / (2.0 * a);
461                                 if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON)
462                                         roots[count++] = t;
463                                 t = (-b - sqrt(b2ac)) / (2.0 * a);
464                                 if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON)
465                                         roots[count++] = t;
466                         }
467                 }
468                 for (j = 0; j < count; j++) {
469                         v = nsvg__evalBezier(roots[j], v0[i], v1[i], v2[i], v3[i]);
470                         bounds[0+i] = nsvg__minf(bounds[0+i], (float)v);
471                         bounds[2+i] = nsvg__maxf(bounds[2+i], (float)v);
472                 }
473         }
474 }
475
476 static NSVGparser* nsvg__createParser()
477 {
478         NSVGparser* p;
479         p = (NSVGparser*)malloc(sizeof(NSVGparser));
480         if (p == NULL) goto error;
481         memset(p, 0, sizeof(NSVGparser));
482
483         p->image = (NSVGimage*)malloc(sizeof(NSVGimage));
484         if (p->image == NULL) goto error;
485         memset(p->image, 0, sizeof(NSVGimage));
486
487         // Init style
488         nsvg__xformIdentity(p->attr[0].xform);
489         memset(p->attr[0].id, 0, sizeof p->attr[0].id);
490         p->attr[0].fillColor = NSVG_RGB(0,0,0);
491         p->attr[0].strokeColor = NSVG_RGB(0,0,0);
492         p->attr[0].opacity = 1;
493         p->attr[0].fillOpacity = 1;
494         p->attr[0].strokeOpacity = 1;
495         p->attr[0].stopOpacity = 1;
496         p->attr[0].strokeWidth = 1;
497         p->attr[0].strokeLineJoin = NSVG_JOIN_MITER;
498         p->attr[0].strokeLineCap = NSVG_CAP_BUTT;
499         p->attr[0].miterLimit = 4;
500         p->attr[0].fillRule = NSVG_FILLRULE_NONZERO;
501         p->attr[0].hasFill = 1;
502         p->attr[0].visible = 1;
503
504         return p;
505
506 error:
507         if (p) {
508                 if (p->image) free(p->image);
509                 free(p);
510         }
511         return NULL;
512 }
513
514 static void nsvg__deletePaths(NSVGpath* path)
515 {
516         while (path) {
517                 NSVGpath *next = path->next;
518                 if (path->pts != NULL)
519                         free(path->pts);
520                 free(path);
521                 path = next;
522         }
523 }
524
525 static void nsvg__deletePaint(NSVGpaint* paint)
526 {
527         if (paint->type == NSVG_PAINT_LINEAR_GRADIENT || paint->type == NSVG_PAINT_RADIAL_GRADIENT)
528                 free(paint->gradient);
529 }
530
531 static void nsvg__deleteGradientData(NSVGgradientData* grad)
532 {
533         NSVGgradientData* next;
534         while (grad != NULL) {
535                 next = grad->next;
536                 free(grad->stops);
537                 free(grad);
538                 grad = next;
539         }
540 }
541
542 static void nsvg__deleteParser(NSVGparser* p)
543 {
544         if (p != NULL) {
545                 nsvg__deletePaths(p->plist);
546                 nsvg__deleteGradientData(p->gradients);
547                 nsvgDelete(p->image);
548                 free(p->pts);
549                 free(p);
550         }
551 }
552
553 static void nsvg__resetPath(NSVGparser* p)
554 {
555         p->npts = 0;
556 }
557
558 static void nsvg__addPoint(NSVGparser* p, float x, float y)
559 {
560         if (p->npts+1 > p->cpts) {
561                 p->cpts = p->cpts ? p->cpts*2 : 8;
562                 p->pts = (float*)realloc(p->pts, p->cpts*2*sizeof(float));
563                 if (!p->pts) return;
564         }
565         p->pts[p->npts*2+0] = x;
566         p->pts[p->npts*2+1] = y;
567         p->npts++;
568 }
569
570 static void nsvg__moveTo(NSVGparser* p, float x, float y)
571 {
572         if (p->npts > 0) {
573                 p->pts[(p->npts-1)*2+0] = x;
574                 p->pts[(p->npts-1)*2+1] = y;
575         } else {
576                 nsvg__addPoint(p, x, y);
577         }
578 }
579
580 static void nsvg__lineTo(NSVGparser* p, float x, float y)
581 {
582         float px,py, dx,dy;
583         if (p->npts > 0) {
584                 px = p->pts[(p->npts-1)*2+0];
585                 py = p->pts[(p->npts-1)*2+1];
586                 dx = x - px;
587                 dy = y - py;
588                 nsvg__addPoint(p, px + dx/3.0f, py + dy/3.0f);
589                 nsvg__addPoint(p, x - dx/3.0f, y - dy/3.0f);
590                 nsvg__addPoint(p, x, y);
591         }
592 }
593
594 static void nsvg__cubicBezTo(NSVGparser* p, float cpx1, float cpy1, float cpx2, float cpy2, float x, float y)
595 {
596         nsvg__addPoint(p, cpx1, cpy1);
597         nsvg__addPoint(p, cpx2, cpy2);
598         nsvg__addPoint(p, x, y);
599 }
600
601 static NSVGattrib* nsvg__getAttr(NSVGparser* p)
602 {
603         return &p->attr[p->attrHead];
604 }
605
606 static void nsvg__pushAttr(NSVGparser* p)
607 {
608         if (p->attrHead < NSVG_MAX_ATTR-1) {
609                 p->attrHead++;
610                 memcpy(&p->attr[p->attrHead], &p->attr[p->attrHead-1], sizeof(NSVGattrib));
611         }
612 }
613
614 static void nsvg__popAttr(NSVGparser* p)
615 {
616         if (p->attrHead > 0)
617                 p->attrHead--;
618 }
619
620 static float nsvg__actualOrigX(NSVGparser* p)
621 {
622         return p->viewMinx;
623 }
624
625 static float nsvg__actualOrigY(NSVGparser* p)
626 {
627         return p->viewMiny;
628 }
629
630 static float nsvg__actualWidth(NSVGparser* p)
631 {
632         return p->viewWidth;
633 }
634
635 static float nsvg__actualHeight(NSVGparser* p)
636 {
637         return p->viewHeight;
638 }
639
640 static float nsvg__actualLength(NSVGparser* p)
641 {
642         float w = nsvg__actualWidth(p), h = nsvg__actualHeight(p);
643         return sqrtf(w*w + h*h) / sqrtf(2.0f);
644 }
645
646 static float nsvg__convertToPixels(NSVGparser* p, NSVGcoordinate c, float orig, float length)
647 {
648         NSVGattrib* attr = nsvg__getAttr(p);
649         switch (c.units) {
650                 case NSVG_UNITS_USER:           return c.value;
651                 case NSVG_UNITS_PX:                     return c.value;
652                 case NSVG_UNITS_PT:                     return c.value / 72.0f * p->dpi;
653                 case NSVG_UNITS_PC:                     return c.value / 6.0f * p->dpi;
654                 case NSVG_UNITS_MM:                     return c.value / 25.4f * p->dpi;
655                 case NSVG_UNITS_CM:                     return c.value / 2.54f * p->dpi;
656                 case NSVG_UNITS_IN:                     return c.value * p->dpi;
657                 case NSVG_UNITS_EM:                     return c.value * attr->fontSize;
658                 case NSVG_UNITS_EX:                     return c.value * attr->fontSize * 0.52f; // x-height of Helvetica.
659                 case NSVG_UNITS_PERCENT:        return orig + c.value / 100.0f * length;
660                 default:                                        return c.value;
661         }
662         return c.value;
663 }
664
665 static NSVGgradientData* nsvg__findGradientData(NSVGparser* p, const char* id)
666 {
667         NSVGgradientData* grad = p->gradients;
668         while (grad) {
669                 if (strcmp(grad->id, id) == 0)
670                         return grad;
671                 grad = grad->next;
672         }
673         return NULL;
674 }
675
676 /**
677  * In the original file, using char type (without signed or unsigned) can be interpreted
678  * as 'unsigned char' in some build environments, like ARM architecture.
679  * To prevent the unexpected behavior, we replace 'char paintType' with 'signed char paintType' here.
680  */
681 static NSVGgradient* nsvg__createGradient(NSVGparser* p, const char* id, const float* localBounds, signed char* paintType)
682 {
683         NSVGattrib* attr = nsvg__getAttr(p);
684         NSVGgradientData* data = NULL;
685         NSVGgradientData* ref = NULL;
686         NSVGgradientStop* stops = NULL;
687         NSVGgradient* grad;
688         float ox, oy, sw, sh, sl;
689         int nstops = 0;
690
691         data = nsvg__findGradientData(p, id);
692         if (data == NULL) return NULL;
693
694         // TODO: use ref to fill in all unset values too.
695         ref = data;
696         while (ref != NULL) {
697                 if (stops == NULL && ref->stops != NULL) {
698                         stops = ref->stops;
699                         nstops = ref->nstops;
700                         break;
701                 }
702                 ref = nsvg__findGradientData(p, ref->ref);
703         }
704         if (stops == NULL) return NULL;
705
706         grad = (NSVGgradient*)malloc(sizeof(NSVGgradient) + sizeof(NSVGgradientStop)*(nstops-1));
707         if (grad == NULL) return NULL;
708
709         // The shape width and height.
710         if (data->units == NSVG_OBJECT_SPACE) {
711                 ox = localBounds[0];
712                 oy = localBounds[1];
713                 sw = localBounds[2] - localBounds[0];
714                 sh = localBounds[3] - localBounds[1];
715         } else {
716                 ox = nsvg__actualOrigX(p);
717                 oy = nsvg__actualOrigY(p);
718                 sw = nsvg__actualWidth(p);
719                 sh = nsvg__actualHeight(p);
720         }
721         sl = sqrtf(sw*sw + sh*sh) / sqrtf(2.0f);
722
723         if (data->type == NSVG_PAINT_LINEAR_GRADIENT) {
724                 float x1, y1, x2, y2, dx, dy;
725                 x1 = nsvg__convertToPixels(p, data->linear.x1, ox, sw);
726                 y1 = nsvg__convertToPixels(p, data->linear.y1, oy, sh);
727                 x2 = nsvg__convertToPixels(p, data->linear.x2, ox, sw);
728                 y2 = nsvg__convertToPixels(p, data->linear.y2, oy, sh);
729                 // Calculate transform aligned to the line
730                 dx = x2 - x1;
731                 dy = y2 - y1;
732                 grad->xform[0] = dy; grad->xform[1] = -dx;
733                 grad->xform[2] = dx; grad->xform[3] = dy;
734                 grad->xform[4] = x1; grad->xform[5] = y1;
735         } else {
736                 float cx, cy, fx, fy, r;
737                 cx = nsvg__convertToPixels(p, data->radial.cx, ox, sw);
738                 cy = nsvg__convertToPixels(p, data->radial.cy, oy, sh);
739                 fx = nsvg__convertToPixels(p, data->radial.fx, ox, sw);
740                 fy = nsvg__convertToPixels(p, data->radial.fy, oy, sh);
741                 r = nsvg__convertToPixels(p, data->radial.r, 0, sl);
742                 // Calculate transform aligned to the circle
743                 grad->xform[0] = r; grad->xform[1] = 0;
744                 grad->xform[2] = 0; grad->xform[3] = r;
745                 grad->xform[4] = cx; grad->xform[5] = cy;
746                 grad->fx = fx / r;
747                 grad->fy = fy / r;
748         }
749
750         nsvg__xformMultiply(grad->xform, data->xform);
751         nsvg__xformMultiply(grad->xform, attr->xform);
752
753         grad->spread = data->spread;
754         memcpy(grad->stops, stops, nstops*sizeof(NSVGgradientStop));
755         grad->nstops = nstops;
756
757         *paintType = data->type;
758
759         return grad;
760 }
761
762 static float nsvg__getAverageScale(float* t)
763 {
764         float sx = sqrtf(t[0]*t[0] + t[2]*t[2]);
765         float sy = sqrtf(t[1]*t[1] + t[3]*t[3]);
766         return (sx + sy) * 0.5f;
767 }
768
769 static void nsvg__getLocalBounds(float* bounds, NSVGshape *shape, float* xform)
770 {
771         NSVGpath* path;
772         float curve[4*2], curveBounds[4];
773         int i, first = 1;
774         for (path = shape->paths; path != NULL; path = path->next) {
775                 nsvg__xformPoint(&curve[0], &curve[1], path->pts[0], path->pts[1], xform);
776                 for (i = 0; i < path->npts-1; i += 3) {
777                         nsvg__xformPoint(&curve[2], &curve[3], path->pts[(i+1)*2], path->pts[(i+1)*2+1], xform);
778                         nsvg__xformPoint(&curve[4], &curve[5], path->pts[(i+2)*2], path->pts[(i+2)*2+1], xform);
779                         nsvg__xformPoint(&curve[6], &curve[7], path->pts[(i+3)*2], path->pts[(i+3)*2+1], xform);
780                         nsvg__curveBounds(curveBounds, curve);
781                         if (first) {
782                                 bounds[0] = curveBounds[0];
783                                 bounds[1] = curveBounds[1];
784                                 bounds[2] = curveBounds[2];
785                                 bounds[3] = curveBounds[3];
786                                 first = 0;
787                         } else {
788                                 bounds[0] = nsvg__minf(bounds[0], curveBounds[0]);
789                                 bounds[1] = nsvg__minf(bounds[1], curveBounds[1]);
790                                 bounds[2] = nsvg__maxf(bounds[2], curveBounds[2]);
791                                 bounds[3] = nsvg__maxf(bounds[3], curveBounds[3]);
792                         }
793                         curve[0] = curve[6];
794                         curve[1] = curve[7];
795                 }
796         }
797 }
798
799 static void nsvg__addShape(NSVGparser* p)
800 {
801         NSVGattrib* attr = nsvg__getAttr(p);
802         float scale = 1.0f;
803         NSVGshape* shape;
804         NSVGpath* path;
805         int i;
806
807         if (p->plist == NULL)
808                 return;
809
810         shape = (NSVGshape*)malloc(sizeof(NSVGshape));
811
812         /**
813          * In the original file, if shape is NULL it goto error below 'return' and free shape memory.
814          * But, the error is only visited when shape is NULL, so there is not needed to free it.
815          */
816         if (shape == NULL) return;
817         memset(shape, 0, sizeof(NSVGshape));
818
819         memcpy(shape->id, attr->id, sizeof shape->id);
820         scale = nsvg__getAverageScale(attr->xform);
821         shape->strokeWidth = attr->strokeWidth * scale;
822         shape->strokeDashOffset = attr->strokeDashOffset * scale;
823         shape->strokeDashCount = (char)attr->strokeDashCount;
824         for (i = 0; i < attr->strokeDashCount; i++)
825                 shape->strokeDashArray[i] = attr->strokeDashArray[i] * scale;
826         shape->strokeLineJoin = attr->strokeLineJoin;
827         shape->strokeLineCap = attr->strokeLineCap;
828         shape->miterLimit = attr->miterLimit;
829         shape->fillRule = attr->fillRule;
830         shape->opacity = attr->opacity;
831
832         shape->paths = p->plist;
833         p->plist = NULL;
834
835         // Calculate shape bounds
836         shape->bounds[0] = shape->paths->bounds[0];
837         shape->bounds[1] = shape->paths->bounds[1];
838         shape->bounds[2] = shape->paths->bounds[2];
839         shape->bounds[3] = shape->paths->bounds[3];
840         for (path = shape->paths->next; path != NULL; path = path->next) {
841                 shape->bounds[0] = nsvg__minf(shape->bounds[0], path->bounds[0]);
842                 shape->bounds[1] = nsvg__minf(shape->bounds[1], path->bounds[1]);
843                 shape->bounds[2] = nsvg__maxf(shape->bounds[2], path->bounds[2]);
844                 shape->bounds[3] = nsvg__maxf(shape->bounds[3], path->bounds[3]);
845         }
846
847         // Set fill
848         if (attr->hasFill == 0) {
849                 shape->fill.type = NSVG_PAINT_NONE;
850         } else if (attr->hasFill == 1) {
851                 shape->fill.type = NSVG_PAINT_COLOR;
852                 shape->fill.color = attr->fillColor;
853                 shape->fill.color |= (unsigned int)(attr->fillOpacity*255) << 24;
854         } else if (attr->hasFill == 2) {
855                 shape->opacity *= attr->fillOpacity;
856                 float inv[6], localBounds[4];
857                 nsvg__xformInverse(inv, attr->xform);
858                 nsvg__getLocalBounds(localBounds, shape, inv);
859                 shape->fill.gradient = nsvg__createGradient(p, attr->fillGradient, localBounds, &shape->fill.type);
860                 if (shape->fill.gradient == NULL) {
861                         shape->fill.type = NSVG_PAINT_NONE;
862                 }
863         }
864
865         // Set stroke
866         if (attr->hasStroke == 0) {
867                 shape->stroke.type = NSVG_PAINT_NONE;
868         } else if (attr->hasStroke == 1) {
869                 shape->stroke.type = NSVG_PAINT_COLOR;
870                 shape->stroke.color = attr->strokeColor;
871                 shape->stroke.color |= (unsigned int)(attr->strokeOpacity*255) << 24;
872         } else if (attr->hasStroke == 2) {
873                 float inv[6], localBounds[4];
874                 nsvg__xformInverse(inv, attr->xform);
875                 nsvg__getLocalBounds(localBounds, shape, inv);
876                 shape->stroke.gradient = nsvg__createGradient(p, attr->strokeGradient, localBounds, &shape->stroke.type);
877                 if (shape->stroke.gradient == NULL)
878                         shape->stroke.type = NSVG_PAINT_NONE;
879         }
880
881         // Set flags
882         shape->flags = (attr->visible ? NSVG_FLAGS_VISIBLE : 0x00);
883
884         // Add to tail
885         if (p->image->shapes == NULL)
886                 p->image->shapes = shape;
887         else
888                 p->shapesTail->next = shape;
889         p->shapesTail = shape;
890
891         return;
892 }
893
894 static void nsvg__addPath(NSVGparser* p, char closed)
895 {
896         NSVGattrib* attr = nsvg__getAttr(p);
897         NSVGpath* path = NULL;
898         float bounds[4];
899         float* curve;
900         int i;
901
902         if (p->npts < 4)
903                 return;
904
905         if (closed)
906                 nsvg__lineTo(p, p->pts[0], p->pts[1]);
907
908         path = (NSVGpath*)malloc(sizeof(NSVGpath));
909         if (path == NULL) goto error;
910         memset(path, 0, sizeof(NSVGpath));
911
912         path->pts = (float*)malloc(p->npts*2*sizeof(float));
913         if (path->pts == NULL) goto error;
914         path->closed = closed;
915         path->npts = p->npts;
916
917         // Transform path.
918         for (i = 0; i < p->npts; ++i)
919                 nsvg__xformPoint(&path->pts[i*2], &path->pts[i*2+1], p->pts[i*2], p->pts[i*2+1], attr->xform);
920
921         // Find bounds
922         for (i = 0; i < path->npts-1; i += 3) {
923                 curve = &path->pts[i*2];
924                 nsvg__curveBounds(bounds, curve);
925                 if (i == 0) {
926                         path->bounds[0] = bounds[0];
927                         path->bounds[1] = bounds[1];
928                         path->bounds[2] = bounds[2];
929                         path->bounds[3] = bounds[3];
930                 } else {
931                         path->bounds[0] = nsvg__minf(path->bounds[0], bounds[0]);
932                         path->bounds[1] = nsvg__minf(path->bounds[1], bounds[1]);
933                         path->bounds[2] = nsvg__maxf(path->bounds[2], bounds[2]);
934                         path->bounds[3] = nsvg__maxf(path->bounds[3], bounds[3]);
935                 }
936         }
937
938         path->next = p->plist;
939         p->plist = path;
940
941         return;
942
943 error:
944         if (path != NULL) {
945                 if (path->pts != NULL) free(path->pts);
946                 free(path);
947         }
948 }
949
950 // We roll our own string to float because the std library one uses locale and messes things up.
951 static double nsvg__atof(const char* s)
952 {
953         char* cur = (char*)s;
954         char* end = NULL;
955         double res = 0.0, sign = 1.0;
956         long long intPart = 0, fracPart = 0;
957         char hasIntPart = 0, hasFracPart = 0;
958
959         // Parse optional sign
960         if (*cur == '+') {
961                 cur++;
962         } else if (*cur == '-') {
963                 sign = -1;
964                 cur++;
965         }
966
967         // Parse integer part
968         if (nsvg__isdigit(*cur)) {
969                 // Parse digit sequence
970                 intPart = (double)strtoll(cur, &end, 10);
971                 if (cur != end) {
972                         res = (double)intPart;
973                         hasIntPart = 1;
974                         cur = end;
975                 }
976         }
977
978         // Parse fractional part.
979         if (*cur == '.') {
980                 cur++; // Skip '.'
981                 if (nsvg__isdigit(*cur)) {
982                         // Parse digit sequence
983                         fracPart = strtoll(cur, &end, 10);
984                         if (cur != end) {
985                                 res += (double)fracPart / pow(10.0, (double)(end - cur));
986                                 hasFracPart = 1;
987                                 cur = end;
988                         }
989                 }
990         }
991
992         // A valid number should have integer or fractional part.
993         if (!hasIntPart && !hasFracPart)
994                 return 0.0;
995
996         // Parse optional exponent
997         if (*cur == 'e' || *cur == 'E') {
998                 int expPart = 0;
999                 cur++; // skip 'E'
1000                 expPart = strtol(cur, &end, 10); // Parse digit sequence with sign
1001                 if (cur != end) {
1002                         res *= pow(10.0, (double)expPart);
1003                 }
1004         }
1005
1006         return res * sign;
1007 }
1008
1009
1010 static const char* nsvg__parseNumber(const char* s, char* it, const int size)
1011 {
1012         const int last = size-1;
1013         int i = 0;
1014
1015         // sign
1016         if (*s == '-' || *s == '+') {
1017                 if (i < last) it[i++] = *s;
1018                 s++;
1019         }
1020         // integer part
1021         while (*s && nsvg__isdigit(*s)) {
1022                 if (i < last) it[i++] = *s;
1023                 s++;
1024         }
1025         if (*s == '.') {
1026                 // decimal point
1027                 if (i < last) it[i++] = *s;
1028                 s++;
1029                 // fraction part
1030                 while (*s && nsvg__isdigit(*s)) {
1031                         if (i < last) it[i++] = *s;
1032                         s++;
1033                 }
1034         }
1035         // exponent
1036         if (*s == 'e' || *s == 'E') {
1037                 if (i < last) it[i++] = *s;
1038                 s++;
1039                 if (*s == '-' || *s == '+') {
1040                         if (i < last) it[i++] = *s;
1041                         s++;
1042                 }
1043                 while (*s && nsvg__isdigit(*s)) {
1044                         if (i < last) it[i++] = *s;
1045                         s++;
1046                 }
1047         }
1048         it[i] = '\0';
1049
1050         return s;
1051 }
1052
1053 static const char* nsvg__getNextPathItem(const char* s, char* it)
1054 {
1055         it[0] = '\0';
1056         // Skip white spaces and commas
1057         while (*s && (nsvg__isspace(*s) || *s == ',')) s++;
1058         if (!*s) return s;
1059         if (*s == '-' || *s == '+' || *s == '.' || nsvg__isdigit(*s)) {
1060                 s = nsvg__parseNumber(s, it, 64);
1061         } else {
1062                 // Parse command
1063                 it[0] = *s++;
1064                 it[1] = '\0';
1065                 return s;
1066         }
1067
1068         return s;
1069 }
1070
1071 static unsigned int nsvg__parseColorHex(const char* str)
1072 {
1073         unsigned int c = 0, r = 0, g = 0, b = 0;
1074         int n = 0;
1075         str++; // skip #
1076         // Calculate number of characters.
1077         while(str[n] && !nsvg__isspace(str[n]))
1078                 n++;
1079         if (n == 6) {
1080                 sscanf(str, "%x", &c);
1081         } else if (n == 3) {
1082                 sscanf(str, "%x", &c);
1083                 c = (c&0xf) | ((c&0xf0) << 4) | ((c&0xf00) << 8);
1084                 c |= c<<4;
1085         }
1086         r = (c >> 16) & 0xff;
1087         g = (c >> 8) & 0xff;
1088         b = c & 0xff;
1089         return NSVG_RGB(r,g,b);
1090 }
1091
1092 static unsigned int nsvg__parseColorRGB(const char* str)
1093 {
1094         int r = -1, g = -1, b = -1;
1095         char s1[33]="", s2[33]="";
1096         /**
1097          * In the original file, the formatted data reading did not specify the string with width limitation.
1098          * To prevent the possible overflow, we replace '%s' with '%32s' here.
1099          */
1100         sscanf(str + 4, "%d%32[%%, \t]%d%32[%%, \t]%d", &r, s1, &g, s2, &b);
1101         if (strchr(s1, '%')) {
1102                 return NSVG_RGB((r*255)/100,(g*255)/100,(b*255)/100);
1103         } else {
1104                 return NSVG_RGB(r,g,b);
1105         }
1106 }
1107
1108 typedef struct NSVGNamedColor {
1109         const char* name;
1110         unsigned int color;
1111 } NSVGNamedColor;
1112
1113 NSVGNamedColor nsvg__colors[] = {
1114
1115         { "red", NSVG_RGB(255, 0, 0) },
1116         { "green", NSVG_RGB( 0, 128, 0) },
1117         { "blue", NSVG_RGB( 0, 0, 255) },
1118         { "yellow", NSVG_RGB(255, 255, 0) },
1119         { "cyan", NSVG_RGB( 0, 255, 255) },
1120         { "magenta", NSVG_RGB(255, 0, 255) },
1121         { "black", NSVG_RGB( 0, 0, 0) },
1122         { "grey", NSVG_RGB(128, 128, 128) },
1123         { "gray", NSVG_RGB(128, 128, 128) },
1124         { "white", NSVG_RGB(255, 255, 255) },
1125
1126         { "aliceblue", NSVG_RGB(240, 248, 255) },
1127         { "antiquewhite", NSVG_RGB(250, 235, 215) },
1128         { "aqua", NSVG_RGB( 0, 255, 255) },
1129         { "aquamarine", NSVG_RGB(127, 255, 212) },
1130         { "azure", NSVG_RGB(240, 255, 255) },
1131         { "beige", NSVG_RGB(245, 245, 220) },
1132         { "bisque", NSVG_RGB(255, 228, 196) },
1133         { "blanchedalmond", NSVG_RGB(255, 235, 205) },
1134         { "blueviolet", NSVG_RGB(138, 43, 226) },
1135         { "brown", NSVG_RGB(165, 42, 42) },
1136         { "burlywood", NSVG_RGB(222, 184, 135) },
1137         { "cadetblue", NSVG_RGB( 95, 158, 160) },
1138         { "chartreuse", NSVG_RGB(127, 255, 0) },
1139         { "chocolate", NSVG_RGB(210, 105, 30) },
1140         { "coral", NSVG_RGB(255, 127, 80) },
1141         { "cornflowerblue", NSVG_RGB(100, 149, 237) },
1142         { "cornsilk", NSVG_RGB(255, 248, 220) },
1143         { "crimson", NSVG_RGB(220, 20, 60) },
1144         { "darkblue", NSVG_RGB( 0, 0, 139) },
1145         { "darkcyan", NSVG_RGB( 0, 139, 139) },
1146         { "darkgoldenrod", NSVG_RGB(184, 134, 11) },
1147         { "darkgray", NSVG_RGB(169, 169, 169) },
1148         { "darkgreen", NSVG_RGB( 0, 100, 0) },
1149         { "darkgrey", NSVG_RGB(169, 169, 169) },
1150         { "darkkhaki", NSVG_RGB(189, 183, 107) },
1151         { "darkmagenta", NSVG_RGB(139, 0, 139) },
1152         { "darkolivegreen", NSVG_RGB( 85, 107, 47) },
1153         { "darkorange", NSVG_RGB(255, 140, 0) },
1154         { "darkorchid", NSVG_RGB(153, 50, 204) },
1155         { "darkred", NSVG_RGB(139, 0, 0) },
1156         { "darksalmon", NSVG_RGB(233, 150, 122) },
1157         { "darkseagreen", NSVG_RGB(143, 188, 143) },
1158         { "darkslateblue", NSVG_RGB( 72, 61, 139) },
1159         { "darkslategray", NSVG_RGB( 47, 79, 79) },
1160         { "darkslategrey", NSVG_RGB( 47, 79, 79) },
1161         { "darkturquoise", NSVG_RGB( 0, 206, 209) },
1162         { "darkviolet", NSVG_RGB(148, 0, 211) },
1163         { "deeppink", NSVG_RGB(255, 20, 147) },
1164         { "deepskyblue", NSVG_RGB( 0, 191, 255) },
1165         { "dimgray", NSVG_RGB(105, 105, 105) },
1166         { "dimgrey", NSVG_RGB(105, 105, 105) },
1167         { "dodgerblue", NSVG_RGB( 30, 144, 255) },
1168         { "firebrick", NSVG_RGB(178, 34, 34) },
1169         { "floralwhite", NSVG_RGB(255, 250, 240) },
1170         { "forestgreen", NSVG_RGB( 34, 139, 34) },
1171         { "fuchsia", NSVG_RGB(255, 0, 255) },
1172         { "gainsboro", NSVG_RGB(220, 220, 220) },
1173         { "ghostwhite", NSVG_RGB(248, 248, 255) },
1174         { "gold", NSVG_RGB(255, 215, 0) },
1175         { "goldenrod", NSVG_RGB(218, 165, 32) },
1176         { "greenyellow", NSVG_RGB(173, 255, 47) },
1177         { "honeydew", NSVG_RGB(240, 255, 240) },
1178         { "hotpink", NSVG_RGB(255, 105, 180) },
1179         { "indianred", NSVG_RGB(205, 92, 92) },
1180         { "indigo", NSVG_RGB( 75, 0, 130) },
1181         { "ivory", NSVG_RGB(255, 255, 240) },
1182         { "khaki", NSVG_RGB(240, 230, 140) },
1183         { "lavender", NSVG_RGB(230, 230, 250) },
1184         { "lavenderblush", NSVG_RGB(255, 240, 245) },
1185         { "lawngreen", NSVG_RGB(124, 252, 0) },
1186         { "lemonchiffon", NSVG_RGB(255, 250, 205) },
1187         { "lightblue", NSVG_RGB(173, 216, 230) },
1188         { "lightcoral", NSVG_RGB(240, 128, 128) },
1189         { "lightcyan", NSVG_RGB(224, 255, 255) },
1190         { "lightgoldenrodyellow", NSVG_RGB(250, 250, 210) },
1191         { "lightgray", NSVG_RGB(211, 211, 211) },
1192         { "lightgreen", NSVG_RGB(144, 238, 144) },
1193         { "lightgrey", NSVG_RGB(211, 211, 211) },
1194         { "lightpink", NSVG_RGB(255, 182, 193) },
1195         { "lightsalmon", NSVG_RGB(255, 160, 122) },
1196         { "lightseagreen", NSVG_RGB( 32, 178, 170) },
1197         { "lightskyblue", NSVG_RGB(135, 206, 250) },
1198         { "lightslategray", NSVG_RGB(119, 136, 153) },
1199         { "lightslategrey", NSVG_RGB(119, 136, 153) },
1200         { "lightsteelblue", NSVG_RGB(176, 196, 222) },
1201         { "lightyellow", NSVG_RGB(255, 255, 224) },
1202         { "lime", NSVG_RGB( 0, 255, 0) },
1203         { "limegreen", NSVG_RGB( 50, 205, 50) },
1204         { "linen", NSVG_RGB(250, 240, 230) },
1205         { "maroon", NSVG_RGB(128, 0, 0) },
1206         { "mediumaquamarine", NSVG_RGB(102, 205, 170) },
1207         { "mediumblue", NSVG_RGB( 0, 0, 205) },
1208         { "mediumorchid", NSVG_RGB(186, 85, 211) },
1209         { "mediumpurple", NSVG_RGB(147, 112, 219) },
1210         { "mediumseagreen", NSVG_RGB( 60, 179, 113) },
1211         { "mediumslateblue", NSVG_RGB(123, 104, 238) },
1212         { "mediumspringgreen", NSVG_RGB( 0, 250, 154) },
1213         { "mediumturquoise", NSVG_RGB( 72, 209, 204) },
1214         { "mediumvioletred", NSVG_RGB(199, 21, 133) },
1215         { "midnightblue", NSVG_RGB( 25, 25, 112) },
1216         { "mintcream", NSVG_RGB(245, 255, 250) },
1217         { "mistyrose", NSVG_RGB(255, 228, 225) },
1218         { "moccasin", NSVG_RGB(255, 228, 181) },
1219         { "navajowhite", NSVG_RGB(255, 222, 173) },
1220         { "navy", NSVG_RGB( 0, 0, 128) },
1221         { "oldlace", NSVG_RGB(253, 245, 230) },
1222         { "olive", NSVG_RGB(128, 128, 0) },
1223         { "olivedrab", NSVG_RGB(107, 142, 35) },
1224         { "orange", NSVG_RGB(255, 165, 0) },
1225         { "orangered", NSVG_RGB(255, 69, 0) },
1226         { "orchid", NSVG_RGB(218, 112, 214) },
1227         { "palegoldenrod", NSVG_RGB(238, 232, 170) },
1228         { "palegreen", NSVG_RGB(152, 251, 152) },
1229         { "paleturquoise", NSVG_RGB(175, 238, 238) },
1230         { "palevioletred", NSVG_RGB(219, 112, 147) },
1231         { "papayawhip", NSVG_RGB(255, 239, 213) },
1232         { "peachpuff", NSVG_RGB(255, 218, 185) },
1233         { "peru", NSVG_RGB(205, 133, 63) },
1234         { "pink", NSVG_RGB(255, 192, 203) },
1235         { "plum", NSVG_RGB(221, 160, 221) },
1236         { "powderblue", NSVG_RGB(176, 224, 230) },
1237         { "purple", NSVG_RGB(128, 0, 128) },
1238         { "rosybrown", NSVG_RGB(188, 143, 143) },
1239         { "royalblue", NSVG_RGB( 65, 105, 225) },
1240         { "saddlebrown", NSVG_RGB(139, 69, 19) },
1241         { "salmon", NSVG_RGB(250, 128, 114) },
1242         { "sandybrown", NSVG_RGB(244, 164, 96) },
1243         { "seagreen", NSVG_RGB( 46, 139, 87) },
1244         { "seashell", NSVG_RGB(255, 245, 238) },
1245         { "sienna", NSVG_RGB(160, 82, 45) },
1246         { "silver", NSVG_RGB(192, 192, 192) },
1247         { "skyblue", NSVG_RGB(135, 206, 235) },
1248         { "slateblue", NSVG_RGB(106, 90, 205) },
1249         { "slategray", NSVG_RGB(112, 128, 144) },
1250         { "slategrey", NSVG_RGB(112, 128, 144) },
1251         { "snow", NSVG_RGB(255, 250, 250) },
1252         { "springgreen", NSVG_RGB( 0, 255, 127) },
1253         { "steelblue", NSVG_RGB( 70, 130, 180) },
1254         { "tan", NSVG_RGB(210, 180, 140) },
1255         { "teal", NSVG_RGB( 0, 128, 128) },
1256         { "thistle", NSVG_RGB(216, 191, 216) },
1257         { "tomato", NSVG_RGB(255, 99, 71) },
1258         { "turquoise", NSVG_RGB( 64, 224, 208) },
1259         { "violet", NSVG_RGB(238, 130, 238) },
1260         { "wheat", NSVG_RGB(245, 222, 179) },
1261         { "whitesmoke", NSVG_RGB(245, 245, 245) },
1262         { "yellowgreen", NSVG_RGB(154, 205, 50) },
1263 };
1264
1265 static unsigned int nsvg__parseColorName(const char* str)
1266 {
1267         int i, ncolors = sizeof(nsvg__colors) / sizeof(NSVGNamedColor);
1268
1269         for (i = 0; i < ncolors; i++) {
1270                 if (strcmp(nsvg__colors[i].name, str) == 0) {
1271                         return nsvg__colors[i].color;
1272                 }
1273         }
1274
1275         return NSVG_RGB(128, 128, 128);
1276 }
1277
1278 static unsigned int nsvg__parseColor(const char* str)
1279 {
1280         size_t len = 0;
1281         while(*str == ' ') ++str;
1282         len = strlen(str);
1283         if (len >= 1 && *str == '#')
1284                 return nsvg__parseColorHex(str);
1285         else if (len >= 4 && str[0] == 'r' && str[1] == 'g' && str[2] == 'b' && str[3] == '(')
1286                 return nsvg__parseColorRGB(str);
1287         return nsvg__parseColorName(str);
1288 }
1289
1290 static float nsvg__parseOpacity(const char* str)
1291 {
1292         float val = nsvg__atof(str);
1293         if (val < 0.0f) val = 0.0f;
1294         if (val > 1.0f) val = 1.0f;
1295         return val;
1296 }
1297
1298 static float nsvg__parseMiterLimit(const char* str)
1299 {
1300         float val = nsvg__atof(str);
1301         if (val < 0.0f) val = 0.0f;
1302         return val;
1303 }
1304
1305 static int nsvg__parseUnits(const char* units)
1306 {
1307         if (units[0] == 'p' && units[1] == 'x')
1308                 return NSVG_UNITS_PX;
1309         else if (units[0] == 'p' && units[1] == 't')
1310                 return NSVG_UNITS_PT;
1311         else if (units[0] == 'p' && units[1] == 'c')
1312                 return NSVG_UNITS_PC;
1313         else if (units[0] == 'm' && units[1] == 'm')
1314                 return NSVG_UNITS_MM;
1315         else if (units[0] == 'c' && units[1] == 'm')
1316                 return NSVG_UNITS_CM;
1317         else if (units[0] == 'i' && units[1] == 'n')
1318                 return NSVG_UNITS_IN;
1319         else if (units[0] == '%')
1320                 return NSVG_UNITS_PERCENT;
1321         else if (units[0] == 'e' && units[1] == 'm')
1322                 return NSVG_UNITS_EM;
1323         else if (units[0] == 'e' && units[1] == 'x')
1324                 return NSVG_UNITS_EX;
1325         return NSVG_UNITS_USER;
1326 }
1327
1328 static NSVGcoordinate nsvg__parseCoordinateRaw(const char* str)
1329 {
1330         NSVGcoordinate coord = {0, NSVG_UNITS_USER};
1331         char buf[64];
1332         coord.units = nsvg__parseUnits(nsvg__parseNumber(str, buf, 64));
1333         coord.value = nsvg__atof(buf);
1334         return coord;
1335 }
1336
1337 static NSVGcoordinate nsvg__coord(float v, int units)
1338 {
1339         NSVGcoordinate coord = {v, units};
1340         return coord;
1341 }
1342
1343 static float nsvg__parseCoordinate(NSVGparser* p, const char* str, float orig, float length)
1344 {
1345         NSVGcoordinate coord = nsvg__parseCoordinateRaw(str);
1346         return nsvg__convertToPixels(p, coord, orig, length);
1347 }
1348
1349 static int nsvg__parseTransformArgs(const char* str, float* args, int maxNa, int* na)
1350 {
1351         const char* end;
1352         const char* ptr;
1353         char it[64];
1354
1355         *na = 0;
1356         ptr = str;
1357         while (*ptr && *ptr != '(') ++ptr;
1358         if (*ptr == 0)
1359                 return 1;
1360         end = ptr;
1361         while (*end && *end != ')') ++end;
1362         if (*end == 0)
1363                 return 1;
1364
1365         while (ptr < end) {
1366                 if (*ptr == '-' || *ptr == '+' || *ptr == '.' || nsvg__isdigit(*ptr)) {
1367                         if (*na >= maxNa) return 0;
1368                         ptr = nsvg__parseNumber(ptr, it, 64);
1369                         args[(*na)++] = (float)nsvg__atof(it);
1370                 } else {
1371                         ++ptr;
1372                 }
1373         }
1374         return (int)(end - str);
1375 }
1376
1377
1378 static int nsvg__parseMatrix(float* xform, const char* str)
1379 {
1380         float t[6];
1381         int na = 0;
1382         int len = nsvg__parseTransformArgs(str, t, 6, &na);
1383         if (na != 6) return len;
1384         memcpy(xform, t, sizeof(float)*6);
1385         return len;
1386 }
1387
1388 static int nsvg__parseTranslate(float* xform, const char* str)
1389 {
1390         float args[2];
1391         float t[6];
1392         int na = 0;
1393         int len = nsvg__parseTransformArgs(str, args, 2, &na);
1394         if (na == 1) args[1] = 0.0;
1395
1396         nsvg__xformSetTranslation(t, args[0], args[1]);
1397         memcpy(xform, t, sizeof(float)*6);
1398         return len;
1399 }
1400
1401 static int nsvg__parseScale(float* xform, const char* str)
1402 {
1403         float args[2];
1404         int na = 0;
1405         float t[6];
1406         int len = nsvg__parseTransformArgs(str, args, 2, &na);
1407         if (na == 1) args[1] = args[0];
1408         nsvg__xformSetScale(t, args[0], args[1]);
1409         memcpy(xform, t, sizeof(float)*6);
1410         return len;
1411 }
1412
1413 static int nsvg__parseSkewX(float* xform, const char* str)
1414 {
1415         float args[1];
1416         int na = 0;
1417         float t[6];
1418         int len = nsvg__parseTransformArgs(str, args, 1, &na);
1419         nsvg__xformSetSkewX(t, args[0]/180.0f*NSVG_PI);
1420         memcpy(xform, t, sizeof(float)*6);
1421         return len;
1422 }
1423
1424 static int nsvg__parseSkewY(float* xform, const char* str)
1425 {
1426         float args[1];
1427         int na = 0;
1428         float t[6];
1429         int len = nsvg__parseTransformArgs(str, args, 1, &na);
1430         nsvg__xformSetSkewY(t, args[0]/180.0f*NSVG_PI);
1431         memcpy(xform, t, sizeof(float)*6);
1432         return len;
1433 }
1434
1435 static int nsvg__parseRotate(float* xform, const char* str)
1436 {
1437         float args[3];
1438         int na = 0;
1439         float m[6];
1440         float t[6];
1441         int len = nsvg__parseTransformArgs(str, args, 3, &na);
1442         if (na == 1)
1443                 args[1] = args[2] = 0.0f;
1444         nsvg__xformIdentity(m);
1445
1446         if (na > 1) {
1447                 nsvg__xformSetTranslation(t, -args[1], -args[2]);
1448                 nsvg__xformMultiply(m, t);
1449         }
1450
1451         nsvg__xformSetRotation(t, args[0]/180.0f*NSVG_PI);
1452         nsvg__xformMultiply(m, t);
1453
1454         if (na > 1) {
1455                 nsvg__xformSetTranslation(t, args[1], args[2]);
1456                 nsvg__xformMultiply(m, t);
1457         }
1458
1459         memcpy(xform, m, sizeof(float)*6);
1460
1461         return len;
1462 }
1463
1464 static void nsvg__parseTransform(float* xform, const char* str)
1465 {
1466         float t[6];
1467         nsvg__xformIdentity(xform);
1468         while (*str)
1469         {
1470                 if (strncmp(str, "matrix", 6) == 0)
1471                         str += nsvg__parseMatrix(t, str);
1472                 else if (strncmp(str, "translate", 9) == 0)
1473                         str += nsvg__parseTranslate(t, str);
1474                 else if (strncmp(str, "scale", 5) == 0)
1475                         str += nsvg__parseScale(t, str);
1476                 else if (strncmp(str, "rotate", 6) == 0)
1477                         str += nsvg__parseRotate(t, str);
1478                 else if (strncmp(str, "skewX", 5) == 0)
1479                         str += nsvg__parseSkewX(t, str);
1480                 else if (strncmp(str, "skewY", 5) == 0)
1481                         str += nsvg__parseSkewY(t, str);
1482                 else{
1483                         ++str;
1484                         continue;
1485                 }
1486
1487                 nsvg__xformPremultiply(xform, t);
1488         }
1489 }
1490
1491 static void nsvg__parseUrl(char* id, const char* str)
1492 {
1493         int i = 0;
1494         str += 4; // "url(";
1495         if (*str == '#')
1496                 str++;
1497         while (i < 63 && *str != ')') {
1498                 id[i] = *str++;
1499                 i++;
1500         }
1501         id[i] = '\0';
1502 }
1503
1504 static char nsvg__parseLineCap(const char* str)
1505 {
1506         if (strcmp(str, "butt") == 0)
1507                 return NSVG_CAP_BUTT;
1508         else if (strcmp(str, "round") == 0)
1509                 return NSVG_CAP_ROUND;
1510         else if (strcmp(str, "square") == 0)
1511                 return NSVG_CAP_SQUARE;
1512         // TODO: handle inherit.
1513         return NSVG_CAP_BUTT;
1514 }
1515
1516 static char nsvg__parseLineJoin(const char* str)
1517 {
1518         if (strcmp(str, "miter") == 0)
1519                 return NSVG_JOIN_MITER;
1520         else if (strcmp(str, "round") == 0)
1521                 return NSVG_JOIN_ROUND;
1522         else if (strcmp(str, "bevel") == 0)
1523                 return NSVG_JOIN_BEVEL;
1524         // TODO: handle inherit.
1525         return NSVG_CAP_BUTT;
1526 }
1527
1528 static char nsvg__parseFillRule(const char* str)
1529 {
1530         if (strcmp(str, "nonzero") == 0)
1531                 return NSVG_FILLRULE_NONZERO;
1532         else if (strcmp(str, "evenodd") == 0)
1533                 return NSVG_FILLRULE_EVENODD;
1534         // TODO: handle inherit.
1535         return NSVG_FILLRULE_NONZERO;
1536 }
1537
1538 static const char* nsvg__getNextDashItem(const char* s, char* it)
1539 {
1540         int n = 0;
1541         it[0] = '\0';
1542         // Skip white spaces and commas
1543         while (*s && (nsvg__isspace(*s) || *s == ',')) s++;
1544         // Advance until whitespace, comma or end.
1545         while (*s && (!nsvg__isspace(*s) && *s != ',')) {
1546                 if (n < 63)
1547                         it[n++] = *s;
1548                 s++;
1549         }
1550         it[n++] = '\0';
1551         return s;
1552 }
1553
1554 static int nsvg__parseStrokeDashArray(NSVGparser* p, const char* str, float* strokeDashArray)
1555 {
1556         char item[64];
1557         int count = 0, i;
1558         float sum = 0.0f;
1559
1560         // Handle "none"
1561         if (str[0] == 'n')
1562                 return 0;
1563
1564         // Parse dashes
1565         while (*str) {
1566                 str = nsvg__getNextDashItem(str, item);
1567                 if (!*item) break;
1568                 if (count < NSVG_MAX_DASHES)
1569                         strokeDashArray[count++] = fabsf(nsvg__parseCoordinate(p, item, 0.0f, nsvg__actualLength(p)));
1570         }
1571
1572         for (i = 0; i < count; i++)
1573                 sum += strokeDashArray[i];
1574         if (sum <= 1e-6f)
1575                 count = 0;
1576
1577         return count;
1578 }
1579
1580 static void nsvg__parseStyle(NSVGparser* p, const char* str);
1581
1582 static int nsvg__parseAttr(NSVGparser* p, const char* name, const char* value)
1583 {
1584         float xform[6];
1585         NSVGattrib* attr = nsvg__getAttr(p);
1586         if (!attr) return 0;
1587
1588         if (strcmp(name, "style") == 0) {
1589                 nsvg__parseStyle(p, value);
1590         } else if (strcmp(name, "display") == 0) {
1591                 if (strcmp(value, "none") == 0)
1592                         attr->visible = 0;
1593                 // Don't reset ->visible on display:inline, one display:none hides the whole subtree
1594
1595         } else if (strcmp(name, "fill") == 0) {
1596                 if (strcmp(value, "none") == 0) {
1597                         attr->hasFill = 0;
1598                 } else if (strncmp(value, "url(", 4) == 0) {
1599                         attr->hasFill = 2;
1600                         nsvg__parseUrl(attr->fillGradient, value);
1601                 } else {
1602                         attr->hasFill = 1;
1603                         attr->fillColor = nsvg__parseColor(value);
1604                 }
1605         } else if (strcmp(name, "opacity") == 0) {
1606                 attr->opacity = nsvg__parseOpacity(value);
1607         } else if (strcmp(name, "fill-opacity") == 0) {
1608                 attr->fillOpacity = nsvg__parseOpacity(value);
1609         } else if (strcmp(name, "stroke") == 0) {
1610                 if (strcmp(value, "none") == 0) {
1611                         attr->hasStroke = 0;
1612                 } else if (strncmp(value, "url(", 4) == 0) {
1613                         attr->hasStroke = 2;
1614                         nsvg__parseUrl(attr->strokeGradient, value);
1615                 } else {
1616                         attr->hasStroke = 1;
1617                         attr->strokeColor = nsvg__parseColor(value);
1618                 }
1619         } else if (strcmp(name, "stroke-width") == 0) {
1620                 attr->strokeWidth = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p));
1621         } else if (strcmp(name, "stroke-dasharray") == 0) {
1622                 attr->strokeDashCount = nsvg__parseStrokeDashArray(p, value, attr->strokeDashArray);
1623         } else if (strcmp(name, "stroke-dashoffset") == 0) {
1624                 attr->strokeDashOffset = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p));
1625         } else if (strcmp(name, "stroke-opacity") == 0) {
1626                 attr->strokeOpacity = nsvg__parseOpacity(value);
1627         } else if (strcmp(name, "stroke-linecap") == 0) {
1628                 attr->strokeLineCap = nsvg__parseLineCap(value);
1629         } else if (strcmp(name, "stroke-linejoin") == 0) {
1630                 attr->strokeLineJoin = nsvg__parseLineJoin(value);
1631         } else if (strcmp(name, "stroke-miterlimit") == 0) {
1632                 attr->miterLimit = nsvg__parseMiterLimit(value);
1633         } else if (strcmp(name, "fill-rule") == 0) {
1634                 attr->fillRule = nsvg__parseFillRule(value);
1635         } else if (strcmp(name, "font-size") == 0) {
1636                 attr->fontSize = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p));
1637         } else if (strcmp(name, "transform") == 0) {
1638                 nsvg__parseTransform(xform, value);
1639                 nsvg__xformPremultiply(attr->xform, xform);
1640         } else if (strcmp(name, "stop-color") == 0) {
1641                 attr->stopColor = nsvg__parseColor(value);
1642         } else if (strcmp(name, "stop-opacity") == 0) {
1643                 attr->stopOpacity = nsvg__parseOpacity(value);
1644         } else if (strcmp(name, "offset") == 0) {
1645                 attr->stopOffset = nsvg__parseCoordinate(p, value, 0.0f, 1.0f);
1646         } else if (strcmp(name, "id") == 0) {
1647                 strncpy(attr->id, value, 63);
1648                 attr->id[63] = '\0';
1649         } else {
1650                 return 0;
1651         }
1652         return 1;
1653 }
1654
1655 static int nsvg__parseNameValue(NSVGparser* p, const char* start, const char* end)
1656 {
1657         const char* str;
1658         const char* val;
1659         char name[512];
1660         char value[512];
1661         int n;
1662
1663         str = start;
1664         while (str < end && *str != ':') ++str;
1665
1666         val = str;
1667
1668         // Right Trim
1669         while (str > start &&  (*str == ':' || nsvg__isspace(*str))) --str;
1670         ++str;
1671
1672         n = (int)(str - start);
1673         if (n > 511) n = 511;
1674         if (n) memcpy(name, start, n);
1675         name[n] = 0;
1676
1677         while (val < end && (*val == ':' || nsvg__isspace(*val))) ++val;
1678
1679         n = (int)(end - val);
1680         if (n > 511) n = 511;
1681         if (n) memcpy(value, val, n);
1682         value[n] = 0;
1683
1684         return nsvg__parseAttr(p, name, value);
1685 }
1686
1687 static void nsvg__parseStyle(NSVGparser* p, const char* str)
1688 {
1689         const char* start;
1690         const char* end;
1691
1692         while (*str) {
1693                 // Left Trim
1694                 while(*str && nsvg__isspace(*str)) ++str;
1695                 start = str;
1696                 while(*str && *str != ';') ++str;
1697                 end = str;
1698
1699                 // Right Trim
1700                 while (end > start &&  (*end == ';' || nsvg__isspace(*end))) --end;
1701                 ++end;
1702
1703                 nsvg__parseNameValue(p, start, end);
1704                 if (*str) ++str;
1705         }
1706 }
1707
1708 static void nsvg__parseAttribs(NSVGparser* p, const char** attr)
1709 {
1710         int i;
1711         for (i = 0; attr[i]; i += 2)
1712         {
1713                 if (strcmp(attr[i], "style") == 0)
1714                         nsvg__parseStyle(p, attr[i + 1]);
1715                 else
1716                         nsvg__parseAttr(p, attr[i], attr[i + 1]);
1717         }
1718 }
1719
1720 static int nsvg__getArgsPerElement(char cmd)
1721 {
1722         switch (cmd) {
1723                 case 'v':
1724                 case 'V':
1725                 case 'h':
1726                 case 'H':
1727                         return 1;
1728                 case 'm':
1729                 case 'M':
1730                 case 'l':
1731                 case 'L':
1732                 case 't':
1733                 case 'T':
1734                         return 2;
1735                 case 'q':
1736                 case 'Q':
1737                 case 's':
1738                 case 'S':
1739                         return 4;
1740                 case 'c':
1741                 case 'C':
1742                         return 6;
1743                 case 'a':
1744                 case 'A':
1745                         return 7;
1746         }
1747         return 0;
1748 }
1749
1750 static void nsvg__pathMoveTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
1751 {
1752         if (rel) {
1753                 *cpx += args[0];
1754                 *cpy += args[1];
1755         } else {
1756                 *cpx = args[0];
1757                 *cpy = args[1];
1758         }
1759         nsvg__moveTo(p, *cpx, *cpy);
1760 }
1761
1762 static void nsvg__pathLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
1763 {
1764         if (rel) {
1765                 *cpx += args[0];
1766                 *cpy += args[1];
1767         } else {
1768                 *cpx = args[0];
1769                 *cpy = args[1];
1770         }
1771         nsvg__lineTo(p, *cpx, *cpy);
1772 }
1773
1774 static void nsvg__pathHLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
1775 {
1776         if (rel)
1777                 *cpx += args[0];
1778         else
1779                 *cpx = args[0];
1780         nsvg__lineTo(p, *cpx, *cpy);
1781 }
1782
1783 static void nsvg__pathVLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
1784 {
1785         if (rel)
1786                 *cpy += args[0];
1787         else
1788                 *cpy = args[0];
1789         nsvg__lineTo(p, *cpx, *cpy);
1790 }
1791
1792 static void nsvg__pathCubicBezTo(NSVGparser* p, float* cpx, float* cpy,
1793                                                                  float* cpx2, float* cpy2, float* args, int rel)
1794 {
1795         float x2, y2, cx1, cy1, cx2, cy2;
1796
1797         if (rel) {
1798                 cx1 = *cpx + args[0];
1799                 cy1 = *cpy + args[1];
1800                 cx2 = *cpx + args[2];
1801                 cy2 = *cpy + args[3];
1802                 x2 = *cpx + args[4];
1803                 y2 = *cpy + args[5];
1804         } else {
1805                 cx1 = args[0];
1806                 cy1 = args[1];
1807                 cx2 = args[2];
1808                 cy2 = args[3];
1809                 x2 = args[4];
1810                 y2 = args[5];
1811         }
1812
1813         nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2);
1814
1815         *cpx2 = cx2;
1816         *cpy2 = cy2;
1817         *cpx = x2;
1818         *cpy = y2;
1819 }
1820
1821 static void nsvg__pathCubicBezShortTo(NSVGparser* p, float* cpx, float* cpy,
1822                                                                           float* cpx2, float* cpy2, float* args, int rel)
1823 {
1824         float x1, y1, x2, y2, cx1, cy1, cx2, cy2;
1825
1826         x1 = *cpx;
1827         y1 = *cpy;
1828         if (rel) {
1829                 cx2 = *cpx + args[0];
1830                 cy2 = *cpy + args[1];
1831                 x2 = *cpx + args[2];
1832                 y2 = *cpy + args[3];
1833         } else {
1834                 cx2 = args[0];
1835                 cy2 = args[1];
1836                 x2 = args[2];
1837                 y2 = args[3];
1838         }
1839
1840         cx1 = 2*x1 - *cpx2;
1841         cy1 = 2*y1 - *cpy2;
1842
1843         nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2);
1844
1845         *cpx2 = cx2;
1846         *cpy2 = cy2;
1847         *cpx = x2;
1848         *cpy = y2;
1849 }
1850
1851 static void nsvg__pathQuadBezTo(NSVGparser* p, float* cpx, float* cpy,
1852                                                                 float* cpx2, float* cpy2, float* args, int rel)
1853 {
1854         float x1, y1, x2, y2, cx, cy;
1855         float cx1, cy1, cx2, cy2;
1856
1857         x1 = *cpx;
1858         y1 = *cpy;
1859         if (rel) {
1860                 cx = *cpx + args[0];
1861                 cy = *cpy + args[1];
1862                 x2 = *cpx + args[2];
1863                 y2 = *cpy + args[3];
1864         } else {
1865                 cx = args[0];
1866                 cy = args[1];
1867                 x2 = args[2];
1868                 y2 = args[3];
1869         }
1870
1871         // Convert to cubic bezier
1872         cx1 = x1 + 2.0f/3.0f*(cx - x1);
1873         cy1 = y1 + 2.0f/3.0f*(cy - y1);
1874         cx2 = x2 + 2.0f/3.0f*(cx - x2);
1875         cy2 = y2 + 2.0f/3.0f*(cy - y2);
1876
1877         nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2);
1878
1879         *cpx2 = cx;
1880         *cpy2 = cy;
1881         *cpx = x2;
1882         *cpy = y2;
1883 }
1884
1885 static void nsvg__pathQuadBezShortTo(NSVGparser* p, float* cpx, float* cpy,
1886                                                                          float* cpx2, float* cpy2, float* args, int rel)
1887 {
1888         float x1, y1, x2, y2, cx, cy;
1889         float cx1, cy1, cx2, cy2;
1890
1891         x1 = *cpx;
1892         y1 = *cpy;
1893         if (rel) {
1894                 x2 = *cpx + args[0];
1895                 y2 = *cpy + args[1];
1896         } else {
1897                 x2 = args[0];
1898                 y2 = args[1];
1899         }
1900
1901         cx = 2*x1 - *cpx2;
1902         cy = 2*y1 - *cpy2;
1903
1904         // Convert to cubix bezier
1905         cx1 = x1 + 2.0f/3.0f*(cx - x1);
1906         cy1 = y1 + 2.0f/3.0f*(cy - y1);
1907         cx2 = x2 + 2.0f/3.0f*(cx - x2);
1908         cy2 = y2 + 2.0f/3.0f*(cy - y2);
1909
1910         nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2);
1911
1912         *cpx2 = cx;
1913         *cpy2 = cy;
1914         *cpx = x2;
1915         *cpy = y2;
1916 }
1917
1918 static float nsvg__sqr(float x) { return x*x; }
1919 static float nsvg__vmag(float x, float y) { return sqrtf(x*x + y*y); }
1920
1921 static float nsvg__vecrat(float ux, float uy, float vx, float vy)
1922 {
1923         return (ux*vx + uy*vy) / (nsvg__vmag(ux,uy) * nsvg__vmag(vx,vy));
1924 }
1925
1926 static float nsvg__vecang(float ux, float uy, float vx, float vy)
1927 {
1928         float r = nsvg__vecrat(ux,uy, vx,vy);
1929         if (r < -1.0f) r = -1.0f;
1930         if (r > 1.0f) r = 1.0f;
1931         return ((ux*vy < uy*vx) ? -1.0f : 1.0f) * acosf(r);
1932 }
1933
1934 static void nsvg__pathArcTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
1935 {
1936         // Ported from canvg (https://code.google.com/p/canvg/)
1937         float rx, ry, rotx;
1938         float x1, y1, x2, y2, cx, cy, dx, dy, d;
1939         float x1p, y1p, cxp, cyp, s, sa, sb;
1940         float ux, uy, vx, vy, a1, da;
1941         float x, y, tanx, tany, a, px = 0, py = 0, ptanx = 0, ptany = 0, t[6];
1942         float sinrx, cosrx;
1943         int fa, fs;
1944         int i, ndivs;
1945         float hda, kappa;
1946
1947         rx = fabsf(args[0]);                            // y radius
1948         ry = fabsf(args[1]);                            // x radius
1949         rotx = args[2] / 180.0f * NSVG_PI;              // x rotation angle
1950         fa = fabsf(args[3]) > 1e-6 ? 1 : 0;     // Large arc
1951         fs = fabsf(args[4]) > 1e-6 ? 1 : 0;     // Sweep direction
1952         x1 = *cpx;                                                      // start point
1953         y1 = *cpy;
1954         if (rel) {                                                      // end point
1955                 x2 = *cpx + args[5];
1956                 y2 = *cpy + args[6];
1957         } else {
1958                 x2 = args[5];
1959                 y2 = args[6];
1960         }
1961
1962         dx = x1 - x2;
1963         dy = y1 - y2;
1964         d = sqrtf(dx*dx + dy*dy);
1965         if (d < 1e-6f || rx < 1e-6f || ry < 1e-6f) {
1966                 // The arc degenerates to a line
1967                 nsvg__lineTo(p, x2, y2);
1968                 *cpx = x2;
1969                 *cpy = y2;
1970                 return;
1971         }
1972
1973         sinrx = sinf(rotx);
1974         cosrx = cosf(rotx);
1975
1976         // Convert to center point parameterization.
1977         // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
1978         // 1) Compute x1', y1'
1979         x1p = cosrx * dx / 2.0f + sinrx * dy / 2.0f;
1980         y1p = -sinrx * dx / 2.0f + cosrx * dy / 2.0f;
1981         d = nsvg__sqr(x1p)/nsvg__sqr(rx) + nsvg__sqr(y1p)/nsvg__sqr(ry);
1982         if (d > 1) {
1983                 d = sqrtf(d);
1984                 rx *= d;
1985                 ry *= d;
1986         }
1987         // 2) Compute cx', cy'
1988         s = 0.0f;
1989         sa = nsvg__sqr(rx)*nsvg__sqr(ry) - nsvg__sqr(rx)*nsvg__sqr(y1p) - nsvg__sqr(ry)*nsvg__sqr(x1p);
1990         sb = nsvg__sqr(rx)*nsvg__sqr(y1p) + nsvg__sqr(ry)*nsvg__sqr(x1p);
1991         if (sa < 0.0f) sa = 0.0f;
1992         if (sb > 0.0f)
1993                 s = sqrtf(sa / sb);
1994         if (fa == fs)
1995                 s = -s;
1996         cxp = s * rx * y1p / ry;
1997         cyp = s * -ry * x1p / rx;
1998
1999         // 3) Compute cx,cy from cx',cy'
2000         cx = (x1 + x2)/2.0f + cosrx*cxp - sinrx*cyp;
2001         cy = (y1 + y2)/2.0f + sinrx*cxp + cosrx*cyp;
2002
2003         // 4) Calculate theta1, and delta theta.
2004         ux = (x1p - cxp) / rx;
2005         uy = (y1p - cyp) / ry;
2006         vx = (-x1p - cxp) / rx;
2007         vy = (-y1p - cyp) / ry;
2008         a1 = nsvg__vecang(1.0f,0.0f, ux,uy);    // Initial angle
2009         da = nsvg__vecang(ux,uy, vx,vy);                // Delta angle
2010
2011 //      if (vecrat(ux,uy,vx,vy) <= -1.0f) da = NSVG_PI;
2012 //      if (vecrat(ux,uy,vx,vy) >= 1.0f) da = 0;
2013
2014         if (fs == 0 && da > 0)
2015                 da -= 2 * NSVG_PI;
2016         else if (fs == 1 && da < 0)
2017                 da += 2 * NSVG_PI;
2018
2019         // Approximate the arc using cubic spline segments.
2020         t[0] = cosrx; t[1] = sinrx;
2021         t[2] = -sinrx; t[3] = cosrx;
2022         t[4] = cx; t[5] = cy;
2023
2024         // Split arc into max 90 degree segments.
2025         // The loop assumes an iteration per end point (including start and end), this +1.
2026         ndivs = (int)(fabsf(da) / (NSVG_PI*0.5f) + 1.0f);
2027         hda = (da / (float)ndivs) / 2.0f;
2028         kappa = fabsf(4.0f / 3.0f * (1.0f - cosf(hda)) / sinf(hda));
2029         if (da < 0.0f)
2030                 kappa = -kappa;
2031
2032         for (i = 0; i <= ndivs; i++) {
2033                 a = a1 + da * ((float)i/(float)ndivs);
2034                 dx = cosf(a);
2035                 dy = sinf(a);
2036                 nsvg__xformPoint(&x, &y, dx*rx, dy*ry, t); // position
2037                 nsvg__xformVec(&tanx, &tany, -dy*rx * kappa, dx*ry * kappa, t); // tangent
2038                 if (i > 0)
2039                         nsvg__cubicBezTo(p, px+ptanx,py+ptany, x-tanx, y-tany, x, y);
2040                 px = x;
2041                 py = y;
2042                 ptanx = tanx;
2043                 ptany = tany;
2044         }
2045
2046         *cpx = x2;
2047         *cpy = y2;
2048 }
2049
2050 static void nsvg__parsePath(NSVGparser* p, const char** attr)
2051 {
2052         const char* s = NULL;
2053         char cmd = '\0';
2054         float args[10];
2055         int nargs;
2056         int rargs = 0;
2057         float cpx, cpy, cpx2, cpy2;
2058         const char* tmp[4];
2059         char closedFlag;
2060         int i;
2061         char item[64];
2062
2063         for (i = 0; attr[i]; i += 2) {
2064                 if (strcmp(attr[i], "d") == 0) {
2065                         s = attr[i + 1];
2066                 } else {
2067                         tmp[0] = attr[i];
2068                         tmp[1] = attr[i + 1];
2069                         tmp[2] = 0;
2070                         tmp[3] = 0;
2071                         nsvg__parseAttribs(p, tmp);
2072                 }
2073         }
2074
2075         if (s) {
2076                 nsvg__resetPath(p);
2077                 cpx = 0; cpy = 0;
2078                 cpx2 = 0; cpy2 = 0;
2079                 closedFlag = 0;
2080                 nargs = 0;
2081
2082                 while (*s) {
2083                         s = nsvg__getNextPathItem(s, item);
2084                         if (!*item) break;
2085                         if (nsvg__isnum(item[0])) {
2086                                 if (nargs < 10)
2087                                         args[nargs++] = (float)nsvg__atof(item);
2088                                 if (nargs >= rargs) {
2089                                         switch (cmd) {
2090                                                 case 'm':
2091                                                 case 'M':
2092                                                         nsvg__pathMoveTo(p, &cpx, &cpy, args, cmd == 'm' ? 1 : 0);
2093                                                         // Moveto can be followed by multiple coordinate pairs,
2094                                                         // which should be treated as linetos.
2095                                                         cmd = (cmd == 'm') ? 'l' : 'L';
2096                                                         rargs = nsvg__getArgsPerElement(cmd);
2097                                                         cpx2 = cpx; cpy2 = cpy;
2098                                                         break;
2099                                                 case 'l':
2100                                                 case 'L':
2101                                                         nsvg__pathLineTo(p, &cpx, &cpy, args, cmd == 'l' ? 1 : 0);
2102                                                         cpx2 = cpx; cpy2 = cpy;
2103                                                         break;
2104                                                 case 'H':
2105                                                 case 'h':
2106                                                         nsvg__pathHLineTo(p, &cpx, &cpy, args, cmd == 'h' ? 1 : 0);
2107                                                         cpx2 = cpx; cpy2 = cpy;
2108                                                         break;
2109                                                 case 'V':
2110                                                 case 'v':
2111                                                         nsvg__pathVLineTo(p, &cpx, &cpy, args, cmd == 'v' ? 1 : 0);
2112                                                         cpx2 = cpx; cpy2 = cpy;
2113                                                         break;
2114                                                 case 'C':
2115                                                 case 'c':
2116                                                         nsvg__pathCubicBezTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 'c' ? 1 : 0);
2117                                                         break;
2118                                                 case 'S':
2119                                                 case 's':
2120                                                         nsvg__pathCubicBezShortTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 's' ? 1 : 0);
2121                                                         break;
2122                                                 case 'Q':
2123                                                 case 'q':
2124                                                         nsvg__pathQuadBezTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 'q' ? 1 : 0);
2125                                                         break;
2126                                                 case 'T':
2127                                                 case 't':
2128                                                         nsvg__pathQuadBezShortTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 't' ? 1 : 0);
2129                                                         break;
2130                                                 case 'A':
2131                                                 case 'a':
2132                                                         nsvg__pathArcTo(p, &cpx, &cpy, args, cmd == 'a' ? 1 : 0);
2133                                                         cpx2 = cpx; cpy2 = cpy;
2134                                                         break;
2135                                                 default:
2136                                                         if (nargs >= 2) {
2137                                                                 cpx = args[nargs-2];
2138                                                                 cpy = args[nargs-1];
2139                                                                 cpx2 = cpx; cpy2 = cpy;
2140                                                         }
2141                                                         break;
2142                                         }
2143                                         nargs = 0;
2144                                 }
2145                         } else {
2146                                 cmd = item[0];
2147                                 rargs = nsvg__getArgsPerElement(cmd);
2148                                 if (cmd == 'M' || cmd == 'm') {
2149                                         // Commit path.
2150                                         if (p->npts > 0)
2151                                                 nsvg__addPath(p, closedFlag);
2152                                         // Start new subpath.
2153                                         nsvg__resetPath(p);
2154                                         closedFlag = 0;
2155                                         nargs = 0;
2156                                 } else if (cmd == 'Z' || cmd == 'z') {
2157                                         closedFlag = 1;
2158                                         // Commit path.
2159                                         if (p->npts > 0) {
2160                                                 // Move current point to first point
2161                                                 cpx = p->pts[0];
2162                                                 cpy = p->pts[1];
2163                                                 cpx2 = cpx; cpy2 = cpy;
2164                                                 nsvg__addPath(p, closedFlag);
2165                                         }
2166                                         // Start new subpath.
2167                                         nsvg__resetPath(p);
2168                                         nsvg__moveTo(p, cpx, cpy);
2169                                         closedFlag = 0;
2170                                         nargs = 0;
2171                                 }
2172                         }
2173                 }
2174                 // Commit path.
2175                 if (p->npts)
2176                         nsvg__addPath(p, closedFlag);
2177         }
2178
2179         nsvg__addShape(p);
2180 }
2181
2182 static void nsvg__parseRect(NSVGparser* p, const char** attr)
2183 {
2184         float x = 0.0f;
2185         float y = 0.0f;
2186         float w = 0.0f;
2187         float h = 0.0f;
2188         float rx = -1.0f; // marks not set
2189         float ry = -1.0f;
2190         int i;
2191
2192         for (i = 0; attr[i]; i += 2) {
2193                 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2194                         if (strcmp(attr[i], "x") == 0) x = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2195                         if (strcmp(attr[i], "y") == 0) y = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2196                         if (strcmp(attr[i], "width") == 0) w = nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p));
2197                         if (strcmp(attr[i], "height") == 0) h = nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p));
2198                         if (strcmp(attr[i], "rx") == 0) rx = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p)));
2199                         if (strcmp(attr[i], "ry") == 0) ry = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p)));
2200                 }
2201         }
2202
2203         if (rx < 0.0f && ry > 0.0f) rx = ry;
2204         if (ry < 0.0f && rx > 0.0f) ry = rx;
2205         if (rx < 0.0f) rx = 0.0f;
2206         if (ry < 0.0f) ry = 0.0f;
2207         if (rx > w/2.0f) rx = w/2.0f;
2208         if (ry > h/2.0f) ry = h/2.0f;
2209
2210         if (w != 0.0f && h != 0.0f) {
2211                 nsvg__resetPath(p);
2212
2213                 if (rx < 0.00001f || ry < 0.0001f) {
2214                         nsvg__moveTo(p, x, y);
2215                         nsvg__lineTo(p, x+w, y);
2216                         nsvg__lineTo(p, x+w, y+h);
2217                         nsvg__lineTo(p, x, y+h);
2218                 } else {
2219                         // Rounded rectangle
2220                         nsvg__moveTo(p, x+rx, y);
2221                         nsvg__lineTo(p, x+w-rx, y);
2222                         nsvg__cubicBezTo(p, x+w-rx*(1-NSVG_KAPPA90), y, x+w, y+ry*(1-NSVG_KAPPA90), x+w, y+ry);
2223                         nsvg__lineTo(p, x+w, y+h-ry);
2224                         nsvg__cubicBezTo(p, x+w, y+h-ry*(1-NSVG_KAPPA90), x+w-rx*(1-NSVG_KAPPA90), y+h, x+w-rx, y+h);
2225                         nsvg__lineTo(p, x+rx, y+h);
2226                         nsvg__cubicBezTo(p, x+rx*(1-NSVG_KAPPA90), y+h, x, y+h-ry*(1-NSVG_KAPPA90), x, y+h-ry);
2227                         nsvg__lineTo(p, x, y+ry);
2228                         nsvg__cubicBezTo(p, x, y+ry*(1-NSVG_KAPPA90), x+rx*(1-NSVG_KAPPA90), y, x+rx, y);
2229                 }
2230
2231                 nsvg__addPath(p, 1);
2232
2233                 nsvg__addShape(p);
2234         }
2235 }
2236
2237 static void nsvg__parseCircle(NSVGparser* p, const char** attr)
2238 {
2239         float cx = 0.0f;
2240         float cy = 0.0f;
2241         float r = 0.0f;
2242         int i;
2243
2244         for (i = 0; attr[i]; i += 2) {
2245                 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2246                         if (strcmp(attr[i], "cx") == 0) cx = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2247                         if (strcmp(attr[i], "cy") == 0) cy = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2248                         if (strcmp(attr[i], "r") == 0) r = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualLength(p)));
2249                 }
2250         }
2251
2252         if (r > 0.0f) {
2253                 nsvg__resetPath(p);
2254
2255                 nsvg__moveTo(p, cx+r, cy);
2256                 nsvg__cubicBezTo(p, cx+r, cy+r*NSVG_KAPPA90, cx+r*NSVG_KAPPA90, cy+r, cx, cy+r);
2257                 nsvg__cubicBezTo(p, cx-r*NSVG_KAPPA90, cy+r, cx-r, cy+r*NSVG_KAPPA90, cx-r, cy);
2258                 nsvg__cubicBezTo(p, cx-r, cy-r*NSVG_KAPPA90, cx-r*NSVG_KAPPA90, cy-r, cx, cy-r);
2259                 nsvg__cubicBezTo(p, cx+r*NSVG_KAPPA90, cy-r, cx+r, cy-r*NSVG_KAPPA90, cx+r, cy);
2260
2261                 nsvg__addPath(p, 1);
2262
2263                 nsvg__addShape(p);
2264         }
2265 }
2266
2267 static void nsvg__parseEllipse(NSVGparser* p, const char** attr)
2268 {
2269         float cx = 0.0f;
2270         float cy = 0.0f;
2271         float rx = 0.0f;
2272         float ry = 0.0f;
2273         int i;
2274
2275         for (i = 0; attr[i]; i += 2) {
2276                 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2277                         if (strcmp(attr[i], "cx") == 0) cx = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2278                         if (strcmp(attr[i], "cy") == 0) cy = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2279                         if (strcmp(attr[i], "rx") == 0) rx = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p)));
2280                         if (strcmp(attr[i], "ry") == 0) ry = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p)));
2281                 }
2282         }
2283
2284         if (rx > 0.0f && ry > 0.0f) {
2285
2286                 nsvg__resetPath(p);
2287
2288                 nsvg__moveTo(p, cx+rx, cy);
2289                 nsvg__cubicBezTo(p, cx+rx, cy+ry*NSVG_KAPPA90, cx+rx*NSVG_KAPPA90, cy+ry, cx, cy+ry);
2290                 nsvg__cubicBezTo(p, cx-rx*NSVG_KAPPA90, cy+ry, cx-rx, cy+ry*NSVG_KAPPA90, cx-rx, cy);
2291                 nsvg__cubicBezTo(p, cx-rx, cy-ry*NSVG_KAPPA90, cx-rx*NSVG_KAPPA90, cy-ry, cx, cy-ry);
2292                 nsvg__cubicBezTo(p, cx+rx*NSVG_KAPPA90, cy-ry, cx+rx, cy-ry*NSVG_KAPPA90, cx+rx, cy);
2293
2294                 nsvg__addPath(p, 1);
2295
2296                 nsvg__addShape(p);
2297         }
2298 }
2299
2300 static void nsvg__parseLine(NSVGparser* p, const char** attr)
2301 {
2302         float x1 = 0.0;
2303         float y1 = 0.0;
2304         float x2 = 0.0;
2305         float y2 = 0.0;
2306         int i;
2307
2308         for (i = 0; attr[i]; i += 2) {
2309                 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2310                         if (strcmp(attr[i], "x1") == 0) x1 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2311                         if (strcmp(attr[i], "y1") == 0) y1 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2312                         if (strcmp(attr[i], "x2") == 0) x2 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2313                         if (strcmp(attr[i], "y2") == 0) y2 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2314                 }
2315         }
2316
2317         nsvg__resetPath(p);
2318
2319         nsvg__moveTo(p, x1, y1);
2320         nsvg__lineTo(p, x2, y2);
2321
2322         nsvg__addPath(p, 0);
2323
2324         nsvg__addShape(p);
2325 }
2326
2327 static void nsvg__parsePoly(NSVGparser* p, const char** attr, int closeFlag)
2328 {
2329         int i;
2330         const char* s;
2331         float args[2];
2332         int nargs, npts = 0;
2333         char item[64];
2334
2335         nsvg__resetPath(p);
2336
2337         for (i = 0; attr[i]; i += 2) {
2338                 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2339                         if (strcmp(attr[i], "points") == 0) {
2340                                 s = attr[i + 1];
2341                                 nargs = 0;
2342                                 while (*s) {
2343                                         s = nsvg__getNextPathItem(s, item);
2344                                         args[nargs++] = (float)nsvg__atof(item);
2345                                         if (nargs >= 2) {
2346                                                 if (npts == 0)
2347                                                         nsvg__moveTo(p, args[0], args[1]);
2348                                                 else
2349                                                         nsvg__lineTo(p, args[0], args[1]);
2350                                                 nargs = 0;
2351                                                 npts++;
2352                                         }
2353                                 }
2354                         }
2355                 }
2356         }
2357
2358         nsvg__addPath(p, (char)closeFlag);
2359
2360         nsvg__addShape(p);
2361 }
2362
2363 static void nsvg__parseSVG(NSVGparser* p, const char** attr)
2364 {
2365         int i;
2366         for (i = 0; attr[i]; i += 2) {
2367                 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2368                         if (strcmp(attr[i], "width") == 0) {
2369                                 p->image->width = nsvg__parseCoordinate(p, attr[i + 1], 0.0f, 1.0f);
2370                         } else if (strcmp(attr[i], "height") == 0) {
2371                                 p->image->height = nsvg__parseCoordinate(p, attr[i + 1], 0.0f, 1.0f);
2372                         } else if (strcmp(attr[i], "viewBox") == 0) {
2373                                 const char *s = attr[i + 1];
2374                                 char buf[64];
2375                                 s = nsvg__parseNumber(s, buf, 64);
2376                                 p->viewMinx = nsvg__atof(buf);
2377                                 while (*s && (nsvg__isspace(*s) || *s == '%' || *s == ',')) s++;
2378                                 if (!*s) return;
2379                                 s = nsvg__parseNumber(s, buf, 64);
2380                                 p->viewMiny = nsvg__atof(buf);
2381                                 while (*s && (nsvg__isspace(*s) || *s == '%' || *s == ',')) s++;
2382                                 if (!*s) return;
2383                                 s = nsvg__parseNumber(s, buf, 64);
2384                                 p->viewWidth = nsvg__atof(buf);
2385                                 while (*s && (nsvg__isspace(*s) || *s == '%' || *s == ',')) s++;
2386                                 if (!*s) return;
2387                                 s = nsvg__parseNumber(s, buf, 64);
2388                                 p->viewHeight = nsvg__atof(buf);
2389                         } else if (strcmp(attr[i], "preserveAspectRatio") == 0) {
2390                                 if (strstr(attr[i + 1], "none") != 0) {
2391                                         // No uniform scaling
2392                                         p->alignType = NSVG_ALIGN_NONE;
2393                                 } else {
2394                                         // Parse X align
2395                                         if (strstr(attr[i + 1], "xMin") != 0)
2396                                                 p->alignX = NSVG_ALIGN_MIN;
2397                                         else if (strstr(attr[i + 1], "xMid") != 0)
2398                                                 p->alignX = NSVG_ALIGN_MID;
2399                                         else if (strstr(attr[i + 1], "xMax") != 0)
2400                                                 p->alignX = NSVG_ALIGN_MAX;
2401                                         // Parse X align
2402                                         if (strstr(attr[i + 1], "yMin") != 0)
2403                                                 p->alignY = NSVG_ALIGN_MIN;
2404                                         else if (strstr(attr[i + 1], "yMid") != 0)
2405                                                 p->alignY = NSVG_ALIGN_MID;
2406                                         else if (strstr(attr[i + 1], "yMax") != 0)
2407                                                 p->alignY = NSVG_ALIGN_MAX;
2408                                         // Parse meet/slice
2409                                         p->alignType = NSVG_ALIGN_MEET;
2410                                         if (strstr(attr[i + 1], "slice") != 0)
2411                                                 p->alignType = NSVG_ALIGN_SLICE;
2412                                 }
2413                         }
2414                 }
2415         }
2416 }
2417
2418 static void nsvg__parseGradient(NSVGparser* p, const char** attr, char type)
2419 {
2420         int i;
2421         NSVGgradientData* grad = (NSVGgradientData*)malloc(sizeof(NSVGgradientData));
2422         if (grad == NULL) return;
2423         memset(grad, 0, sizeof(NSVGgradientData));
2424         grad->units = NSVG_OBJECT_SPACE;
2425         grad->type = type;
2426         if (grad->type == NSVG_PAINT_LINEAR_GRADIENT) {
2427                 grad->linear.x1 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT);
2428                 grad->linear.y1 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT);
2429                 grad->linear.x2 = nsvg__coord(100.0f, NSVG_UNITS_PERCENT);
2430                 grad->linear.y2 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT);
2431         } else if (grad->type == NSVG_PAINT_RADIAL_GRADIENT) {
2432                 grad->radial.cx = nsvg__coord(50.0f, NSVG_UNITS_PERCENT);
2433                 grad->radial.cy = nsvg__coord(50.0f, NSVG_UNITS_PERCENT);
2434                 grad->radial.r = nsvg__coord(50.0f, NSVG_UNITS_PERCENT);
2435         }
2436
2437         nsvg__xformIdentity(grad->xform);
2438
2439         for (i = 0; attr[i]; i += 2) {
2440                 if (strcmp(attr[i], "id") == 0) {
2441                         strncpy(grad->id, attr[i+1], 63);
2442                         grad->id[63] = '\0';
2443                 } else if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2444                         if (strcmp(attr[i], "gradientUnits") == 0) {
2445                                 if (strcmp(attr[i+1], "objectBoundingBox") == 0)
2446                                         grad->units = NSVG_OBJECT_SPACE;
2447                                 else
2448                                         grad->units = NSVG_USER_SPACE;
2449                         } else if (strcmp(attr[i], "gradientTransform") == 0) {
2450                                 nsvg__parseTransform(grad->xform, attr[i + 1]);
2451                         } else if (strcmp(attr[i], "cx") == 0) {
2452                                 grad->radial.cx = nsvg__parseCoordinateRaw(attr[i + 1]);
2453                         } else if (strcmp(attr[i], "cy") == 0) {
2454                                 grad->radial.cy = nsvg__parseCoordinateRaw(attr[i + 1]);
2455                         } else if (strcmp(attr[i], "r") == 0) {
2456                                 grad->radial.r = nsvg__parseCoordinateRaw(attr[i + 1]);
2457                         } else if (strcmp(attr[i], "fx") == 0) {
2458                                 grad->radial.fx = nsvg__parseCoordinateRaw(attr[i + 1]);
2459                         } else if (strcmp(attr[i], "fy") == 0) {
2460                                 grad->radial.fy = nsvg__parseCoordinateRaw(attr[i + 1]);
2461                         } else if (strcmp(attr[i], "x1") == 0) {
2462                                 grad->linear.x1 = nsvg__parseCoordinateRaw(attr[i + 1]);
2463                         } else if (strcmp(attr[i], "y1") == 0) {
2464                                 grad->linear.y1 = nsvg__parseCoordinateRaw(attr[i + 1]);
2465                         } else if (strcmp(attr[i], "x2") == 0) {
2466                                 grad->linear.x2 = nsvg__parseCoordinateRaw(attr[i + 1]);
2467                         } else if (strcmp(attr[i], "y2") == 0) {
2468                                 grad->linear.y2 = nsvg__parseCoordinateRaw(attr[i + 1]);
2469                         } else if (strcmp(attr[i], "spreadMethod") == 0) {
2470                                 if (strcmp(attr[i+1], "pad") == 0)
2471                                         grad->spread = NSVG_SPREAD_PAD;
2472                                 else if (strcmp(attr[i+1], "reflect") == 0)
2473                                         grad->spread = NSVG_SPREAD_REFLECT;
2474                                 else if (strcmp(attr[i+1], "repeat") == 0)
2475                                         grad->spread = NSVG_SPREAD_REPEAT;
2476                         } else if (strcmp(attr[i], "xlink:href") == 0) {
2477                                 const char *href = attr[i+1];
2478                                 strncpy(grad->ref, href+1, 62);
2479                                 grad->ref[62] = '\0';
2480                         }
2481                 }
2482         }
2483
2484         grad->next = p->gradients;
2485         p->gradients = grad;
2486 }
2487
2488 static void nsvg__parseGradientStop(NSVGparser* p, const char** attr)
2489 {
2490         NSVGattrib* curAttr = nsvg__getAttr(p);
2491         NSVGgradientData* grad;
2492         NSVGgradientStop* stop;
2493         int i, idx;
2494
2495         curAttr->stopOffset = 0;
2496         curAttr->stopColor = 0;
2497         curAttr->stopOpacity = 1.0f;
2498
2499         for (i = 0; attr[i]; i += 2) {
2500                 nsvg__parseAttr(p, attr[i], attr[i + 1]);
2501         }
2502
2503         // Add stop to the last gradient.
2504         grad = p->gradients;
2505         if (grad == NULL) return;
2506
2507         grad->nstops++;
2508         grad->stops = (NSVGgradientStop*)realloc(grad->stops, sizeof(NSVGgradientStop)*grad->nstops);
2509         if (grad->stops == NULL) return;
2510
2511         // Insert
2512         idx = grad->nstops-1;
2513         for (i = 0; i < grad->nstops-1; i++) {
2514                 if (curAttr->stopOffset < grad->stops[i].offset) {
2515                         idx = i;
2516                         break;
2517                 }
2518         }
2519         if (idx != grad->nstops-1) {
2520                 for (i = grad->nstops-1; i > idx; i--)
2521                         grad->stops[i] = grad->stops[i-1];
2522         }
2523
2524         stop = &grad->stops[idx];
2525         stop->color = curAttr->stopColor;
2526         stop->color |= (unsigned int)(curAttr->stopOpacity*255) << 24;
2527         stop->offset = curAttr->stopOffset;
2528 }
2529
2530 static void nsvg__startElement(void* ud, const char* el, const char** attr)
2531 {
2532         NSVGparser* p = (NSVGparser*)ud;
2533
2534         if (p->defsFlag) {
2535                 // Skip everything but gradients in defs
2536                 if (strcmp(el, "linearGradient") == 0) {
2537                         nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT);
2538                 } else if (strcmp(el, "radialGradient") == 0) {
2539                         nsvg__parseGradient(p, attr, NSVG_PAINT_RADIAL_GRADIENT);
2540                 } else if (strcmp(el, "stop") == 0) {
2541                         nsvg__parseGradientStop(p, attr);
2542                 }
2543                 return;
2544         }
2545
2546         if (strcmp(el, "g") == 0) {
2547                 nsvg__pushAttr(p);
2548                 nsvg__parseAttribs(p, attr);
2549         } else if (strcmp(el, "path") == 0) {
2550                 if (p->pathFlag)        // Do not allow nested paths.
2551                         return;
2552                 nsvg__pushAttr(p);
2553                 nsvg__parsePath(p, attr);
2554                 nsvg__popAttr(p);
2555         } else if (strcmp(el, "rect") == 0) {
2556                 nsvg__pushAttr(p);
2557                 nsvg__parseRect(p, attr);
2558                 nsvg__popAttr(p);
2559         } else if (strcmp(el, "circle") == 0) {
2560                 nsvg__pushAttr(p);
2561                 nsvg__parseCircle(p, attr);
2562                 nsvg__popAttr(p);
2563         } else if (strcmp(el, "ellipse") == 0) {
2564                 nsvg__pushAttr(p);
2565                 nsvg__parseEllipse(p, attr);
2566                 nsvg__popAttr(p);
2567         } else if (strcmp(el, "line") == 0)  {
2568                 nsvg__pushAttr(p);
2569                 nsvg__parseLine(p, attr);
2570                 nsvg__popAttr(p);
2571         } else if (strcmp(el, "polyline") == 0)  {
2572                 nsvg__pushAttr(p);
2573                 nsvg__parsePoly(p, attr, 0);
2574                 nsvg__popAttr(p);
2575         } else if (strcmp(el, "polygon") == 0)  {
2576                 nsvg__pushAttr(p);
2577                 nsvg__parsePoly(p, attr, 1);
2578                 nsvg__popAttr(p);
2579         } else  if (strcmp(el, "linearGradient") == 0) {
2580                 nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT);
2581         } else if (strcmp(el, "radialGradient") == 0) {
2582                 nsvg__parseGradient(p, attr, NSVG_PAINT_RADIAL_GRADIENT);
2583         } else if (strcmp(el, "stop") == 0) {
2584                 nsvg__parseGradientStop(p, attr);
2585         } else if (strcmp(el, "defs") == 0) {
2586                 p->defsFlag = 1;
2587         } else if (strcmp(el, "svg") == 0) {
2588                 nsvg__parseSVG(p, attr);
2589         }
2590 }
2591
2592 static void nsvg__endElement(void* ud, const char* el)
2593 {
2594         NSVGparser* p = (NSVGparser*)ud;
2595
2596         if (strcmp(el, "g") == 0) {
2597                 nsvg__popAttr(p);
2598         } else if (strcmp(el, "path") == 0) {
2599                 p->pathFlag = 0;
2600         } else if (strcmp(el, "defs") == 0) {
2601                 p->defsFlag = 0;
2602         }
2603 }
2604
2605 static void nsvg__content(void* ud, const char* s)
2606 {
2607         NSVG_NOTUSED(ud);
2608         NSVG_NOTUSED(s);
2609         // empty
2610 }
2611
2612 static void nsvg__imageBounds(NSVGparser* p, float* bounds)
2613 {
2614         NSVGshape* shape;
2615         shape = p->image->shapes;
2616         if (shape == NULL) {
2617                 bounds[0] = bounds[1] = bounds[2] = bounds[3] = 0.0;
2618                 return;
2619         }
2620         bounds[0] = shape->bounds[0];
2621         bounds[1] = shape->bounds[1];
2622         bounds[2] = shape->bounds[2];
2623         bounds[3] = shape->bounds[3];
2624         for (shape = shape->next; shape != NULL; shape = shape->next) {
2625                 bounds[0] = nsvg__minf(bounds[0], shape->bounds[0]);
2626                 bounds[1] = nsvg__minf(bounds[1], shape->bounds[1]);
2627                 bounds[2] = nsvg__maxf(bounds[2], shape->bounds[2]);
2628                 bounds[3] = nsvg__maxf(bounds[3], shape->bounds[3]);
2629         }
2630 }
2631
2632 static float nsvg__viewAlign(float content, float container, int type)
2633 {
2634         if (type == NSVG_ALIGN_MIN)
2635                 return 0;
2636         else if (type == NSVG_ALIGN_MAX)
2637                 return container - content;
2638         // mid
2639         return (container - content) * 0.5f;
2640 }
2641
2642 static void nsvg__scaleGradient(NSVGgradient* grad, float tx, float ty, float sx, float sy)
2643 {
2644         float t[6];
2645         nsvg__xformSetTranslation(t, tx, ty);
2646         nsvg__xformMultiply (grad->xform, t);
2647
2648         nsvg__xformSetScale(t, sx, sy);
2649         nsvg__xformMultiply (grad->xform, t);
2650 }
2651
2652 static void nsvg__scaleToViewbox(NSVGparser* p, const char* units)
2653 {
2654         NSVGshape* shape;
2655         NSVGpath* path;
2656         float tx, ty, sx, sy, us, bounds[4], t[6], avgs;
2657         int i;
2658         float* pt;
2659
2660         // Guess image size if not set completely.
2661         nsvg__imageBounds(p, bounds);
2662
2663         if (p->viewWidth == 0) {
2664                 if (p->image->width > 0) {
2665                         p->viewWidth = p->image->width;
2666                 } else {
2667                         p->viewMinx = bounds[0];
2668                         p->viewWidth = bounds[2] - bounds[0];
2669                 }
2670         }
2671         if (p->viewHeight == 0) {
2672                 if (p->image->height > 0) {
2673                         p->viewHeight = p->image->height;
2674                 } else {
2675                         p->viewMiny = bounds[1];
2676                         p->viewHeight = bounds[3] - bounds[1];
2677                 }
2678         }
2679
2680         /**
2681          * We have sample images with the width and height set to 1, whereas the viewbox aspect ratio 
2682          * is not square. Use the viewbox in this case.
2683          */
2684         if (p->image->width <= 1)
2685                 p->image->width = p->viewWidth;
2686         if (p->image->height <= 1)
2687                 p->image->height = p->viewHeight;
2688
2689         tx = -p->viewMinx;
2690         ty = -p->viewMiny;
2691         sx = p->viewWidth > 0 ? p->image->width / p->viewWidth : 0;
2692         sy = p->viewHeight > 0 ? p->image->height / p->viewHeight : 0;
2693         // Unit scaling
2694         us = 1.0f / nsvg__convertToPixels(p, nsvg__coord(1.0f, nsvg__parseUnits(units)), 0.0f, 1.0f);
2695
2696         // Fix aspect ratio
2697         if (p->alignType == NSVG_ALIGN_MEET) {
2698                 // fit whole image into viewbox
2699                 sx = sy = nsvg__minf(sx, sy);
2700                 tx += nsvg__viewAlign(p->viewWidth*sx, p->image->width, p->alignX) / sx;
2701                 ty += nsvg__viewAlign(p->viewHeight*sy, p->image->height, p->alignY) / sy;
2702         } else if (p->alignType == NSVG_ALIGN_SLICE) {
2703                 // fill whole viewbox with image
2704                 sx = sy = nsvg__maxf(sx, sy);
2705                 tx += nsvg__viewAlign(p->viewWidth*sx, p->image->width, p->alignX) / sx;
2706                 ty += nsvg__viewAlign(p->viewHeight*sy, p->image->height, p->alignY) / sy;
2707         }
2708
2709         // Transform
2710         sx *= us;
2711         sy *= us;
2712         avgs = (sx+sy) / 2.0f;
2713         for (shape = p->image->shapes; shape != NULL; shape = shape->next) {
2714                 shape->bounds[0] = (shape->bounds[0] + tx) * sx;
2715                 shape->bounds[1] = (shape->bounds[1] + ty) * sy;
2716                 shape->bounds[2] = (shape->bounds[2] + tx) * sx;
2717                 shape->bounds[3] = (shape->bounds[3] + ty) * sy;
2718                 for (path = shape->paths; path != NULL; path = path->next) {
2719                         path->bounds[0] = (path->bounds[0] + tx) * sx;
2720                         path->bounds[1] = (path->bounds[1] + ty) * sy;
2721                         path->bounds[2] = (path->bounds[2] + tx) * sx;
2722                         path->bounds[3] = (path->bounds[3] + ty) * sy;
2723                         for (i =0; i < path->npts; i++) {
2724                                 pt = &path->pts[i*2];
2725                                 pt[0] = (pt[0] + tx) * sx;
2726                                 pt[1] = (pt[1] + ty) * sy;
2727                         }
2728                 }
2729
2730                 if (shape->fill.type == NSVG_PAINT_LINEAR_GRADIENT || shape->fill.type == NSVG_PAINT_RADIAL_GRADIENT) {
2731                         nsvg__scaleGradient(shape->fill.gradient, tx,ty, sx,sy);
2732                         memcpy(t, shape->fill.gradient->xform, sizeof(float)*6);
2733                         nsvg__xformInverse(shape->fill.gradient->xform, t);
2734                 }
2735                 if (shape->stroke.type == NSVG_PAINT_LINEAR_GRADIENT || shape->stroke.type == NSVG_PAINT_RADIAL_GRADIENT) {
2736                         nsvg__scaleGradient(shape->stroke.gradient, tx,ty, sx,sy);
2737                         memcpy(t, shape->stroke.gradient->xform, sizeof(float)*6);
2738                         nsvg__xformInverse(shape->stroke.gradient->xform, t);
2739                 }
2740
2741                 shape->strokeWidth *= avgs;
2742                 shape->strokeDashOffset *= avgs;
2743                 for (i = 0; i < shape->strokeDashCount; i++)
2744                         shape->strokeDashArray[i] *= avgs;
2745         }
2746 }
2747
2748 NSVGimage* nsvgParse(char* input, const char* units, float dpi)
2749 {
2750         NSVGparser* p;
2751         NSVGimage* ret = 0;
2752
2753         p = nsvg__createParser();
2754         if (p == NULL) {
2755                 return NULL;
2756         }
2757         p->dpi = dpi;
2758
2759         nsvg__parseXML(input, nsvg__startElement, nsvg__endElement, nsvg__content, p);
2760
2761         // Scale to viewBox
2762         nsvg__scaleToViewbox(p, units);
2763
2764         ret = p->image;
2765         p->image = NULL;
2766
2767         nsvg__deleteParser(p);
2768
2769         return ret;
2770 }
2771
2772 NSVGimage* nsvgParseFromFile(const char* filename, const char* units, float dpi)
2773 {
2774         FILE* fp = NULL;
2775         size_t size = 0;
2776         long value = 0;
2777         char* data = NULL;
2778         NSVGimage* image = NULL;
2779
2780         fp = fopen(filename, "rb");
2781         if (!fp) goto error;
2782         fseek(fp, 0, SEEK_END);
2783         value = ftell(fp);
2784         /**
2785          * In the original file, unsigned long type 'size' gets a return value. But, the return value of 'ftell()' is
2786          * signed long type. To prevent interpreting an unexpected large value, we put the comparitive condition here.
2787          */
2788         if( value < 0 ) goto error;
2789         size = value;
2790         fseek(fp, 0, SEEK_SET);
2791         data = (char*)malloc(size+1);
2792         if (data == NULL) goto error;
2793         if (fread(data, 1, size, fp) != size) goto error;
2794         data[size] = '\0';      // Must be null terminated.
2795         fclose(fp);
2796         image = nsvgParse(data, units, dpi);
2797         free(data);
2798
2799         return image;
2800
2801 error:
2802         if (fp) fclose(fp);
2803         if (data) free(data);
2804         /**
2805          * In the original file, image has null check and free it here. But because image has data after all of the 'goto error',
2806          * 'free(image)' was unreachable. So, we removed it.
2807          */
2808         return NULL;
2809 }
2810
2811 void nsvgDelete(NSVGimage* image)
2812 {
2813     if (image == NULL) return;
2814         NSVGshape *snext, *shape;
2815         shape = image->shapes;
2816         while (shape != NULL) {
2817                 snext = shape->next;
2818                 nsvg__deletePaths(shape->paths);
2819                 nsvg__deletePaint(&shape->fill);
2820                 nsvg__deletePaint(&shape->stroke);
2821                 free(shape);
2822                 shape = snext;
2823         }
2824         free(image);
2825 }