Debian Codegraph @

thirdparty/thorvg/src/loaders/svg/tvgSvgLoader.cpp

raw symbols SCIP
1 /*
2 * Copyright (c) 2020 - 2024 the ThorVG project. All rights reserved.
3
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10
11 * The above copyright notice and this permission notice shall be included in all
12 * copies or substantial portions of the Software.
13
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 * SOFTWARE.
21 */
22
23 /*
24 * Copyright notice for the EFL:
25
26 * Copyright (C) EFL developers (see AUTHORS)
27
28 * All rights reserved.
29
30 * Redistribution and use in source and binary forms, with or without
31 * modification, are permitted provided that the following conditions are met:
32
33 * 1. Redistributions of source code must retain the above copyright
34 * notice, this list of conditions and the following disclaimer.
35 * 2. Redistributions in binary form must reproduce the above copyright
36 * notice, this list of conditions and the following disclaimer in the
37 * documentation and/or other materials provided with the distribution.
38
39 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
40 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
41 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
42 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
43 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
44 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
45 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
46 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
47 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
48 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
49 */
50
51 #include <cstring>
52 #include <fstream>
53 #include <float.h>
54 #include "tvgLoader.h"
55 #include "tvgXmlParser.h"
56 #include "tvgSvgLoader.h"
57 #include "tvgSvgSceneBuilder.h"
58 #include "tvgStr.h"
59 #include "tvgSvgCssStyle.h"
60 #include "tvgMath.h"
61
62 /************************************************************************/
63 /* Internal Class Implementation */
64 /************************************************************************/
65
66 /*
67 * According to: https://www.w3.org/TR/SVG2/coords.html#Units
68 * and: https://www.w3.org/TR/css-values-4/#absolute-lengths
69 */
70 #define PX_PER_IN 96 //1 in = 96 px
71 #define PX_PER_PC 16 //1 pc = 1/6 in -> PX_PER_IN/6
72 #define PX_PER_PT 1.333333f //1 pt = 1/72 in -> PX_PER_IN/72
73 #define PX_PER_MM 3.779528f //1 in = 25.4 mm -> PX_PER_IN/25.4
74 #define PX_PER_CM 37.79528f //1 in = 2.54 cm -> PX_PER_IN/2.54
75
76 typedef bool (*parseAttributes)(const char* buf, unsigned bufLength, simpleXMLAttributeCb func, const void* data);
77 typedef SvgNode* (*FactoryMethod)(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func);
78 typedef SvgStyleGradient* (*GradientFactoryMethod)(SvgLoaderData* loader, const char* buf, unsigned bufLength);
79
80 static char* _skipSpace(const char* str, const char* end)
81 {
82 while (((end && str < end) || (!end && *str != '\0')) && isspace(*str)) {
83 ++str;
84 }
85 return (char*) str;
86 }
87
88
89 static char* _copyId(const char* str)
90 {
91 if (!str) return nullptr;
92 if (strlen(str) == 0) return nullptr;
93
94 return strdup(str);
95 }
96
97
98 static const char* _skipComma(const char* content)
99 {
100 content = _skipSpace(content, nullptr);
101 if (*content == ',') return content + 1;
102 return content;
103 }
104
105
106 static bool _parseNumber(const char** content, const char** end, float* number)
107 {
108 const char* _end = end ? *end : nullptr;
109
110 *number = strToFloat(*content, (char**)&_end);
111 //If the start of string is not number
112 if ((*content) == _end) {
113 if (end) *end = _end;
114 return false;
115 }
116 //Skip comma if any
117 *content = _skipComma(_end);
118 if (end) *end = _end;
119
120 return true;
121 }
122
123
124 static constexpr struct
125 {
126 AspectRatioAlign align;
127 const char* tag;
128 } alignTags[] = {
129 { AspectRatioAlign::XMinYMin, "xMinYMin" },
130 { AspectRatioAlign::XMidYMin, "xMidYMin" },
131 { AspectRatioAlign::XMaxYMin, "xMaxYMin" },
132 { AspectRatioAlign::XMinYMid, "xMinYMid" },
133 { AspectRatioAlign::XMidYMid, "xMidYMid" },
134 { AspectRatioAlign::XMaxYMid, "xMaxYMid" },
135 { AspectRatioAlign::XMinYMax, "xMinYMax" },
136 { AspectRatioAlign::XMidYMax, "xMidYMax" },
137 { AspectRatioAlign::XMaxYMax, "xMaxYMax" },
138 };
139
140
141 static void _parseAspectRatio(const char** content, AspectRatioAlign* align, AspectRatioMeetOrSlice* meetOrSlice)
142 {
143 if (!strcmp(*content, "none")) {
144 *align = AspectRatioAlign::None;
145 return;
146 }
147
148 for (unsigned int i = 0; i < sizeof(alignTags) / sizeof(alignTags[0]); i++) {
149 if (!strncmp(*content, alignTags[i].tag, 8)) {
150 *align = alignTags[i].align;
151 *content += 8;
152 *content = _skipSpace(*content, nullptr);
153 break;
154 }
155 }
156
157 if (!strcmp(*content, "meet")) {
158 *meetOrSlice = AspectRatioMeetOrSlice::Meet;
159 } else if (!strcmp(*content, "slice")) {
160 *meetOrSlice = AspectRatioMeetOrSlice::Slice;
161 }
162 }
163
164
165 /**
166 * According to https://www.w3.org/TR/SVG/coords.html#Units
167 */
168 static float _toFloat(const SvgParser* svgParse, const char* str, SvgParserLengthType type)
169 {
170 float parsedValue = strToFloat(str, nullptr);
171
172 if (strstr(str, "cm")) parsedValue *= PX_PER_CM;
173 else if (strstr(str, "mm")) parsedValue *= PX_PER_MM;
174 else if (strstr(str, "pt")) parsedValue *= PX_PER_PT;
175 else if (strstr(str, "pc")) parsedValue *= PX_PER_PC;
176 else if (strstr(str, "in")) parsedValue *= PX_PER_IN;
177 else if (strstr(str, "%")) {
178 if (type == SvgParserLengthType::Vertical) parsedValue = (parsedValue / 100.0f) * svgParse->global.h;
179 else if (type == SvgParserLengthType::Horizontal) parsedValue = (parsedValue / 100.0f) * svgParse->global.w;
180 else if (type == SvgParserLengthType::Diagonal) parsedValue = (sqrtf(powf(svgParse->global.w, 2) + powf(svgParse->global.h, 2)) / sqrtf(2.0f)) * (parsedValue / 100.0f);
181 else //if other than it's radius
182 {
183 float max = svgParse->global.w;
184 if (max < svgParse->global.h)
185 max = svgParse->global.h;
186 parsedValue = (parsedValue / 100.0f) * max;
187 }
188 }
189 //TODO: Implement 'em', 'ex' attributes
190
191 return parsedValue;
192 }
193
194
195 static float _gradientToFloat(const SvgParser* svgParse, const char* str, bool& isPercentage)
196 {
197 char* end = nullptr;
198
199 float parsedValue = strToFloat(str, &end);
200 isPercentage = false;
201
202 if (strstr(str, "%")) {
203 parsedValue = parsedValue / 100.0f;
204 isPercentage = true;
205 }
206 else if (strstr(str, "cm")) parsedValue *= PX_PER_CM;
207 else if (strstr(str, "mm")) parsedValue *= PX_PER_MM;
208 else if (strstr(str, "pt")) parsedValue *= PX_PER_PT;
209 else if (strstr(str, "pc")) parsedValue *= PX_PER_PC;
210 else if (strstr(str, "in")) parsedValue *= PX_PER_IN;
211 //TODO: Implement 'em', 'ex' attributes
212
213 return parsedValue;
214 }
215
216
217 static float _toOffset(const char* str)
218 {
219 char* end = nullptr;
220 auto strEnd = str + strlen(str);
221
222 float parsedValue = strToFloat(str, &end);
223
224 end = _skipSpace(end, nullptr);
225 auto ptr = strstr(str, "%");
226
227 if (ptr) {
228 parsedValue = parsedValue / 100.0f;
229 if (end != ptr || (end + 1) != strEnd) return 0;
230 } else if (end != strEnd) return 0;
231
232 return parsedValue;
233 }
234
235
236 static int _toOpacity(const char* str)
237 {
238 char* end = nullptr;
239 float opacity = strToFloat(str, &end);
240
241 if (end) {
242 if (end[0] == '%' && end[1] == '\0') return lrint(opacity * 2.55f);
243 else if (*end == '\0') return lrint(opacity * 255);
244 }
245 return 255;
246 }
247
248
249 static SvgMaskType _toMaskType(const char* str)
250 {
251 if (!strcmp(str, "Alpha")) return SvgMaskType::Alpha;
252
253 return SvgMaskType::Luminance;
254 }
255
256
257 //The default rendering order: fill, stroke, markers
258 //If any is omitted, will be rendered in its default order after the specified ones.
259 static bool _toPaintOrder(const char* str)
260 {
261 uint8_t position = 1;
262 uint8_t strokePosition = 0;
263 uint8_t fillPosition = 0;
264
265 while (*str != '\0') {
266 str = _skipSpace(str, nullptr);
267 if (!strncmp(str, "fill", 4)) {
268 fillPosition = position++;
269 str += 4;
270 } else if (!strncmp(str, "stroke", 6)) {
271 strokePosition = position++;
272 str += 6;
273 } else if (!strncmp(str, "markers", 7)) {
274 str += 7;
275 } else {
276 return _toPaintOrder("fill stroke");
277 }
278 }
279
280 if (fillPosition == 0) fillPosition = position++;
281 if (strokePosition == 0) strokePosition = position++;
282
283 return fillPosition < strokePosition;
284 }
285
286
287 #define _PARSE_TAG(Type, Name, Name1, Tags_Array, Default) \
288 static Type _to##Name1(const char* str) \
289 { \
290 unsigned int i; \
291 \
292 for (i = 0; i < sizeof(Tags_Array) / sizeof(Tags_Array[0]); i++) { \
293 if (!strcmp(str, Tags_Array[i].tag)) return Tags_Array[i].Name; \
294 } \
295 return Default; \
296 }
297
298
299 /* parse the line cap used during stroking a path.
300 * Value: butt | round | square | inherit
301 * Initial: butt
302 * https://www.w3.org/TR/SVG/painting.html
303 */
304 static constexpr struct
305 {
306 StrokeCap lineCap;
307 const char* tag;
308 } lineCapTags[] = {
309 { StrokeCap::Butt, "butt" },
310 { StrokeCap::Round, "round" },
311 { StrokeCap::Square, "square" }
312 };
313
314
315 _PARSE_TAG(StrokeCap, lineCap, LineCap, lineCapTags, StrokeCap::Butt)
316
317
318 /* parse the line join used during stroking a path.
319 * Value: miter | round | bevel | inherit
320 * Initial: miter
321 * https://www.w3.org/TR/SVG/painting.html
322 */
323 static constexpr struct
324 {
325 StrokeJoin lineJoin;
326 const char* tag;
327 } lineJoinTags[] = {
328 { StrokeJoin::Miter, "miter" },
329 { StrokeJoin::Round, "round" },
330 { StrokeJoin::Bevel, "bevel" }
331 };
332
333
334 _PARSE_TAG(StrokeJoin, lineJoin, LineJoin, lineJoinTags, StrokeJoin::Miter)
335
336
337 /* parse the fill rule used during filling a path.
338 * Value: nonzero | evenodd | inherit
339 * Initial: nonzero
340 * https://www.w3.org/TR/SVG/painting.html
341 */
342 static constexpr struct
343 {
344 FillRule fillRule;
345 const char* tag;
346 } fillRuleTags[] = {
347 { FillRule::EvenOdd, "evenodd" }
348 };
349
350
351 _PARSE_TAG(FillRule, fillRule, FillRule, fillRuleTags, FillRule::Winding)
352
353
354 /* parse the dash pattern used during stroking a path.
355 * Value: none | <dasharray> | inherit
356 * Initial: none
357 * https://www.w3.org/TR/SVG/painting.html
358 */
359 static void _parseDashArray(SvgLoaderData* loader, const char *str, SvgDash* dash)
360 {
361 if (!strncmp(str, "none", 4)) return;
362
363 char *end = nullptr;
364
365 while (*str) {
366 str = _skipComma(str);
367 float parsedValue = strToFloat(str, &end);
368 if (str == end) break;
369 if (parsedValue <= 0.0f) break;
370 if (*end == '%') {
371 ++end;
372 //Refers to the diagonal length of the viewport.
373 //https://www.w3.org/TR/SVG2/coords.html#Units
374 parsedValue = (sqrtf(powf(loader->svgParse->global.w, 2) + powf(loader->svgParse->global.h, 2)) / sqrtf(2.0f)) * (parsedValue / 100.0f);
375 }
376 (*dash).array.push(parsedValue);
377 str = end;
378 }
379 //If dash array size is 1, it means that dash and gap size are the same.
380 if ((*dash).array.count == 1) (*dash).array.push((*dash).array[0]);
381 }
382
383
384 static char* _idFromUrl(const char* url)
385 {
386 auto open = strchr(url, '(');
387 auto close = strchr(url, ')');
388 if (!open || !close || open >= close) return nullptr;
389
390 open = strchr(url, '#');
391 if (!open || open >= close) return nullptr;
392
393 ++open;
394 --close;
395
396 //trim the rest of the spaces and the quote marks if any
397 while (open < close && (*close == ' ' || *close == '\'' || *close == '\"')) --close;
398
399 //quick verification
400 for (auto id = open; id < close; id++) {
401 if (*id == ' ' || *id == '\'') return nullptr;
402 }
403
404 return strDuplicate(open, (close - open + 1));
405 }
406
407
408 static size_t _srcFromUrl(const char* url, char*& src)
409 {
410 src = (char*)strchr(url, '(');
411 auto close = strchr(url, ')');
412 if (!src || !close || src >= close) return 0;
413
414 src = strchr(src, '\'');
415 if (!src || src >= close) return 0;
416 ++src;
417
418 close = strchr(src, '\'');
419 if (!close || close == src) return 0;
420 --close;
421
422 while (src < close && *src == ' ') ++src;
423 while (src < close && *close == ' ') --close;
424
425 return close - src + 1;
426 }
427
428
429 static unsigned char _parseColor(const char* value, char** end)
430 {
431 float r;
432
433 r = strToFloat(value, end);
434 *end = _skipSpace(*end, nullptr);
435 if (**end == '%') {
436 r = 255 * r / 100;
437 (*end)++;
438 }
439 *end = _skipSpace(*end, nullptr);
440
441 if (r < 0 || r > 255) {
442 *end = nullptr;
443 return 0;
444 }
445
446 return lrint(r);
447 }
448
449
450 static constexpr struct
451 {
452 const char* name;
453 unsigned int value;
454 } colors[] = {
455 { "aliceblue", 0xfff0f8ff },
456 { "antiquewhite", 0xfffaebd7 },
457 { "aqua", 0xff00ffff },
458 { "aquamarine", 0xff7fffd4 },
459 { "azure", 0xfff0ffff },
460 { "beige", 0xfff5f5dc },
461 { "bisque", 0xffffe4c4 },
462 { "black", 0xff000000 },
463 { "blanchedalmond", 0xffffebcd },
464 { "blue", 0xff0000ff },
465 { "blueviolet", 0xff8a2be2 },
466 { "brown", 0xffa52a2a },
467 { "burlywood", 0xffdeb887 },
468 { "cadetblue", 0xff5f9ea0 },
469 { "chartreuse", 0xff7fff00 },
470 { "chocolate", 0xffd2691e },
471 { "coral", 0xffff7f50 },
472 { "cornflowerblue", 0xff6495ed },
473 { "cornsilk", 0xfffff8dc },
474 { "crimson", 0xffdc143c },
475 { "cyan", 0xff00ffff },
476 { "darkblue", 0xff00008b },
477 { "darkcyan", 0xff008b8b },
478 { "darkgoldenrod", 0xffb8860b },
479 { "darkgray", 0xffa9a9a9 },
480 { "darkgrey", 0xffa9a9a9 },
481 { "darkgreen", 0xff006400 },
482 { "darkkhaki", 0xffbdb76b },
483 { "darkmagenta", 0xff8b008b },
484 { "darkolivegreen", 0xff556b2f },
485 { "darkorange", 0xffff8c00 },
486 { "darkorchid", 0xff9932cc },
487 { "darkred", 0xff8b0000 },
488 { "darksalmon", 0xffe9967a },
489 { "darkseagreen", 0xff8fbc8f },
490 { "darkslateblue", 0xff483d8b },
491 { "darkslategray", 0xff2f4f4f },
492 { "darkslategrey", 0xff2f4f4f },
493 { "darkturquoise", 0xff00ced1 },
494 { "darkviolet", 0xff9400d3 },
495 { "deeppink", 0xffff1493 },
496 { "deepskyblue", 0xff00bfff },
497 { "dimgray", 0xff696969 },
498 { "dimgrey", 0xff696969 },
499 { "dodgerblue", 0xff1e90ff },
500 { "firebrick", 0xffb22222 },
501 { "floralwhite", 0xfffffaf0 },
502 { "forestgreen", 0xff228b22 },
503 { "fuchsia", 0xffff00ff },
504 { "gainsboro", 0xffdcdcdc },
505 { "ghostwhite", 0xfff8f8ff },
506 { "gold", 0xffffd700 },
507 { "goldenrod", 0xffdaa520 },
508 { "gray", 0xff808080 },
509 { "grey", 0xff808080 },
510 { "green", 0xff008000 },
511 { "greenyellow", 0xffadff2f },
512 { "honeydew", 0xfff0fff0 },
513 { "hotpink", 0xffff69b4 },
514 { "indianred", 0xffcd5c5c },
515 { "indigo", 0xff4b0082 },
516 { "ivory", 0xfffffff0 },
517 { "khaki", 0xfff0e68c },
518 { "lavender", 0xffe6e6fa },
519 { "lavenderblush", 0xfffff0f5 },
520 { "lawngreen", 0xff7cfc00 },
521 { "lemonchiffon", 0xfffffacd },
522 { "lightblue", 0xffadd8e6 },
523 { "lightcoral", 0xfff08080 },
524 { "lightcyan", 0xffe0ffff },
525 { "lightgoldenrodyellow", 0xfffafad2 },
526 { "lightgray", 0xffd3d3d3 },
527 { "lightgrey", 0xffd3d3d3 },
528 { "lightgreen", 0xff90ee90 },
529 { "lightpink", 0xffffb6c1 },
530 { "lightsalmon", 0xffffa07a },
531 { "lightseagreen", 0xff20b2aa },
532 { "lightskyblue", 0xff87cefa },
533 { "lightslategray", 0xff778899 },
534 { "lightslategrey", 0xff778899 },
535 { "lightsteelblue", 0xffb0c4de },
536 { "lightyellow", 0xffffffe0 },
537 { "lime", 0xff00ff00 },
538 { "limegreen", 0xff32cd32 },
539 { "linen", 0xfffaf0e6 },
540 { "magenta", 0xffff00ff },
541 { "maroon", 0xff800000 },
542 { "mediumaquamarine", 0xff66cdaa },
543 { "mediumblue", 0xff0000cd },
544 { "mediumorchid", 0xffba55d3 },
545 { "mediumpurple", 0xff9370d8 },
546 { "mediumseagreen", 0xff3cb371 },
547 { "mediumslateblue", 0xff7b68ee },
548 { "mediumspringgreen", 0xff00fa9a },
549 { "mediumturquoise", 0xff48d1cc },
550 { "mediumvioletred", 0xffc71585 },
551 { "midnightblue", 0xff191970 },
552 { "mintcream", 0xfff5fffa },
553 { "mistyrose", 0xffffe4e1 },
554 { "moccasin", 0xffffe4b5 },
555 { "navajowhite", 0xffffdead },
556 { "navy", 0xff000080 },
557 { "oldlace", 0xfffdf5e6 },
558 { "olive", 0xff808000 },
559 { "olivedrab", 0xff6b8e23 },
560 { "orange", 0xffffa500 },
561 { "orangered", 0xffff4500 },
562 { "orchid", 0xffda70d6 },
563 { "palegoldenrod", 0xffeee8aa },
564 { "palegreen", 0xff98fb98 },
565 { "paleturquoise", 0xffafeeee },
566 { "palevioletred", 0xffd87093 },
567 { "papayawhip", 0xffffefd5 },
568 { "peachpuff", 0xffffdab9 },
569 { "peru", 0xffcd853f },
570 { "pink", 0xffffc0cb },
571 { "plum", 0xffdda0dd },
572 { "powderblue", 0xffb0e0e6 },
573 { "purple", 0xff800080 },
574 { "red", 0xffff0000 },
575 { "rosybrown", 0xffbc8f8f },
576 { "royalblue", 0xff4169e1 },
577 { "saddlebrown", 0xff8b4513 },
578 { "salmon", 0xfffa8072 },
579 { "sandybrown", 0xfff4a460 },
580 { "seagreen", 0xff2e8b57 },
581 { "seashell", 0xfffff5ee },
582 { "sienna", 0xffa0522d },
583 { "silver", 0xffc0c0c0 },
584 { "skyblue", 0xff87ceeb },
585 { "slateblue", 0xff6a5acd },
586 { "slategray", 0xff708090 },
587 { "slategrey", 0xff708090 },
588 { "snow", 0xfffffafa },
589 { "springgreen", 0xff00ff7f },
590 { "steelblue", 0xff4682b4 },
591 { "tan", 0xffd2b48c },
592 { "teal", 0xff008080 },
593 { "thistle", 0xffd8bfd8 },
594 { "tomato", 0xffff6347 },
595 { "turquoise", 0xff40e0d0 },
596 { "violet", 0xffee82ee },
597 { "wheat", 0xfff5deb3 },
598 { "white", 0xffffffff },
599 { "whitesmoke", 0xfff5f5f5 },
600 { "yellow", 0xffffff00 },
601 { "yellowgreen", 0xff9acd32 }
602 };
603
604
605 static bool _hslToRgb(float hue, float saturation, float brightness, uint8_t* red, uint8_t* green, uint8_t* blue)
606 {
607 if (!red || !green || !blue) return false;
608
609 float sv, vsf, f, p, q, t, v;
610 float _red = 0, _green = 0, _blue = 0;
611 uint32_t i = 0;
612
613 while (hue < 0) hue += 360.0f;
614 hue = fmod(hue, 360.0f);
615 saturation = saturation > 0 ? std::min(saturation, 1.0f) : 0.0f;
616 brightness = brightness > 0 ? std::min(brightness, 1.0f) : 0.0f;
617
618 if (tvg::zero(saturation)) _red = _green = _blue = brightness;
619 else {
620 if (tvg::equal(hue, 360.0)) hue = 0.0f;
621 hue /= 60.0f;
622
623 v = (brightness <= 0.5f) ? (brightness * (1.0f + saturation)) : (brightness + saturation - (brightness * saturation));
624 p = brightness + brightness - v;
625
626 if (!tvg::zero(v)) sv = (v - p) / v;
627 else sv = 0;
628
629 i = static_cast<uint8_t>(hue);
630 f = hue - i;
631
632 vsf = v * sv * f;
633
634 t = p + vsf;
635 q = v - vsf;
636
637 switch (i) {
638 case 0: {
639 _red = v;
640 _green = t;
641 _blue = p;
642 break;
643 }
644 case 1: {
645 _red = q;
646 _green = v;
647 _blue = p;
648 break;
649 }
650 case 2: {
651 _red = p;
652 _green = v;
653 _blue = t;
654 break;
655 }
656 case 3: {
657 _red = p;
658 _green = q;
659 _blue = v;
660 break;
661 }
662 case 4: {
663 _red = t;
664 _green = p;
665 _blue = v;
666 break;
667 }
668 case 5: {
669 _red = v;
670 _green = p;
671 _blue = q;
672 break;
673 }
674 }
675 }
676
677 *red = (uint8_t)nearbyint(_red * 255.0f);
678 *green = (uint8_t)nearbyint(_green * 255.0f);
679 *blue = (uint8_t)nearbyint(_blue * 255.0f);
680
681 return true;
682 }
683
684
685 static bool _toColor(const char* str, uint8_t* r, uint8_t* g, uint8_t* b, char** ref)
686 {
687 unsigned int len = strlen(str);
688 char *red, *green, *blue;
689 unsigned char tr, tg, tb;
690
691 if (len == 4 && str[0] == '#') {
692 //Case for "#456" should be interpreted as "#445566"
693 if (isxdigit(str[1]) && isxdigit(str[2]) && isxdigit(str[3])) {
694 char tmp[3] = { '\0', '\0', '\0' };
695 tmp[0] = str[1];
696 tmp[1] = str[1];
697 *r = strtol(tmp, nullptr, 16);
698 tmp[0] = str[2];
699 tmp[1] = str[2];
700 *g = strtol(tmp, nullptr, 16);
701 tmp[0] = str[3];
702 tmp[1] = str[3];
703 *b = strtol(tmp, nullptr, 16);
704 }
705 return true;
706 } else if (len == 7 && str[0] == '#') {
707 if (isxdigit(str[1]) && isxdigit(str[2]) && isxdigit(str[3]) && isxdigit(str[4]) && isxdigit(str[5]) && isxdigit(str[6])) {
708 char tmp[3] = { '\0', '\0', '\0' };
709 tmp[0] = str[1];
710 tmp[1] = str[2];
711 *r = strtol(tmp, nullptr, 16);
712 tmp[0] = str[3];
713 tmp[1] = str[4];
714 *g = strtol(tmp, nullptr, 16);
715 tmp[0] = str[5];
716 tmp[1] = str[6];
717 *b = strtol(tmp, nullptr, 16);
718 }
719 return true;
720 } else if (len >= 10 && (str[0] == 'r' || str[0] == 'R') && (str[1] == 'g' || str[1] == 'G') && (str[2] == 'b' || str[2] == 'B') && str[3] == '(' && str[len - 1] == ')') {
721 tr = _parseColor(str + 4, &red);
722 if (red && *red == ',') {
723 tg = _parseColor(red + 1, &green);
724 if (green && *green == ',') {
725 tb = _parseColor(green + 1, &blue);
726 if (blue && blue[0] == ')' && blue[1] == '\0') {
727 *r = tr;
728 *g = tg;
729 *b = tb;
730 }
731 }
732 }
733 return true;
734 } else if (ref && len >= 3 && !strncmp(str, "url", 3)) {
735 if (*ref) free(*ref);
736 *ref = _idFromUrl((const char*)(str + 3));
737 return true;
738 } else if (len >= 10 && (str[0] == 'h' || str[0] == 'H') && (str[1] == 's' || str[1] == 'S') && (str[2] == 'l' || str[2] == 'L') && str[3] == '(' && str[len - 1] == ')') {
739 float th, ts, tb;
740 const char* content = _skipSpace(str + 4, nullptr);
741 const char* hue = nullptr;
742 if (_parseNumber(&content, &hue, &th) && hue) {
743 const char* saturation = nullptr;
744 hue = _skipSpace(hue, nullptr);
745 hue = (char*)_skipComma(hue);
746 hue = _skipSpace(hue, nullptr);
747 if (_parseNumber(&hue, &saturation, &ts) && saturation && *saturation == '%') {
748 const char* brightness = nullptr;
749 ts /= 100.0f;
750 saturation = _skipSpace(saturation + 1, nullptr);
751 saturation = (char*)_skipComma(saturation);
752 saturation = _skipSpace(saturation, nullptr);
753 if (_parseNumber(&saturation, &brightness, &tb) && brightness && *brightness == '%') {
754 tb /= 100.0f;
755 brightness = _skipSpace(brightness + 1, nullptr);
756 if (brightness && brightness[0] == ')' && brightness[1] == '\0') {
757 return _hslToRgb(th, ts, tb, r, g, b);
758 }
759 }
760 }
761 }
762 } else {
763 //Handle named color
764 for (unsigned int i = 0; i < (sizeof(colors) / sizeof(colors[0])); i++) {
765 if (!strcasecmp(colors[i].name, str)) {
766 *r = (((uint8_t*)(&(colors[i].value)))[2]);
767 *g = (((uint8_t*)(&(colors[i].value)))[1]);
768 *b = (((uint8_t*)(&(colors[i].value)))[0]);
769 return true;
770 }
771 }
772 }
773 return false;
774 }
775
776
777 static char* _parseNumbersArray(char* str, float* points, int* ptCount, int len)
778 {
779 int count = 0;
780 char* end = nullptr;
781
782 str = _skipSpace(str, nullptr);
783 while ((count < len) && (isdigit(*str) || *str == '-' || *str == '+' || *str == '.')) {
784 points[count++] = strToFloat(str, &end);
785 str = end;
786 str = _skipSpace(str, nullptr);
787 if (*str == ',') ++str;
788 //Eat the rest of space
789 str = _skipSpace(str, nullptr);
790 }
791 *ptCount = count;
792 return str;
793 }
794
795
796 enum class MatrixState {
797 Unknown,
798 Matrix,
799 Translate,
800 Rotate,
801 Scale,
802 SkewX,
803 SkewY
804 };
805
806
807 #define MATRIX_DEF(Name, Value) \
808 { \
809 #Name, sizeof(#Name), Value \
810 }
811
812
813 static constexpr struct
814 {
815 const char* tag;
816 int sz;
817 MatrixState state;
818 } matrixTags[] = {
819 MATRIX_DEF(matrix, MatrixState::Matrix),
820 MATRIX_DEF(translate, MatrixState::Translate),
821 MATRIX_DEF(rotate, MatrixState::Rotate),
822 MATRIX_DEF(scale, MatrixState::Scale),
823 MATRIX_DEF(skewX, MatrixState::SkewX),
824 MATRIX_DEF(skewY, MatrixState::SkewY)
825 };
826
827
828 /* parse transform attribute
829 * https://www.w3.org/TR/SVG/coords.html#TransformAttribute
830 */
831 static Matrix* _parseTransformationMatrix(const char* value)
832 {
833 const int POINT_CNT = 8;
834
835 auto matrix = (Matrix*)malloc(sizeof(Matrix));
836 if (!matrix) return nullptr;
837 *matrix = {1, 0, 0, 0, 1, 0, 0, 0, 1};
838
839 float points[POINT_CNT];
840 int ptCount = 0;
841 char* str = (char*)value;
842 char* end = str + strlen(str);
843
844 while (str < end) {
845 auto state = MatrixState::Unknown;
846
847 if (isspace(*str) || (*str == ',')) {
848 ++str;
849 continue;
850 }
851 for (unsigned int i = 0; i < sizeof(matrixTags) / sizeof(matrixTags[0]); i++) {
852 if (!strncmp(matrixTags[i].tag, str, matrixTags[i].sz - 1)) {
853 state = matrixTags[i].state;
854 str += (matrixTags[i].sz - 1);
855 break;
856 }
857 }
858 if (state == MatrixState::Unknown) goto error;
859
860 str = _skipSpace(str, end);
861 if (*str != '(') goto error;
862 ++str;
863 str = _parseNumbersArray(str, points, &ptCount, POINT_CNT);
864 if (*str != ')') goto error;
865 ++str;
866
867 if (state == MatrixState::Matrix) {
868 if (ptCount != 6) goto error;
869 Matrix tmp = {points[0], points[2], points[4], points[1], points[3], points[5], 0, 0, 1};
870 *matrix *= tmp;
871 } else if (state == MatrixState::Translate) {
872 if (ptCount == 1) {
873 Matrix tmp = {1, 0, points[0], 0, 1, 0, 0, 0, 1};
874 *matrix *= tmp;
875 } else if (ptCount == 2) {
876 Matrix tmp = {1, 0, points[0], 0, 1, points[1], 0, 0, 1};
877 *matrix *= tmp;
878 } else goto error;
879 } else if (state == MatrixState::Rotate) {
880 //Transform to signed.
881 points[0] = fmodf(points[0], 360.0f);
882 if (points[0] < 0) points[0] += 360.0f;
883 auto c = cosf(deg2rad(points[0]));
884 auto s = sinf(deg2rad(points[0]));
885 if (ptCount == 1) {
886 Matrix tmp = { c, -s, 0, s, c, 0, 0, 0, 1 };
887 *matrix *= tmp;
888 } else if (ptCount == 3) {
889 Matrix tmp = { 1, 0, points[1], 0, 1, points[2], 0, 0, 1 };
890 *matrix *= tmp;
891 tmp = { c, -s, 0, s, c, 0, 0, 0, 1 };
892 *matrix *= tmp;
893 tmp = { 1, 0, -points[1], 0, 1, -points[2], 0, 0, 1 };
894 *matrix *= tmp;
895 } else {
896 goto error;
897 }
898 } else if (state == MatrixState::Scale) {
899 if (ptCount < 1 || ptCount > 2) goto error;
900 auto sx = points[0];
901 auto sy = sx;
902 if (ptCount == 2) sy = points[1];
903 Matrix tmp = { sx, 0, 0, 0, sy, 0, 0, 0, 1 };
904 *matrix *= tmp;
905 } else if (state == MatrixState::SkewX) {
906 if (ptCount != 1) goto error;
907 auto deg = tanf(deg2rad(points[0]));
908 Matrix tmp = { 1, deg, 0, 0, 1, 0, 0, 0, 1 };
909 *matrix *= tmp;
910 } else if (state == MatrixState::SkewY) {
911 if (ptCount != 1) goto error;
912 auto deg = tanf(deg2rad(points[0]));
913 Matrix tmp = { 1, 0, 0, deg, 1, 0, 0, 0, 1 };
914 *matrix *= tmp;
915 }
916 }
917 return matrix;
918 error:
919 if (matrix) free(matrix);
920 return nullptr;
921 }
922
923
924 #define LENGTH_DEF(Name, Value) \
925 { \
926 #Name, sizeof(#Name), Value \
927 }
928
929
930 static bool _parseStyleAttr(void* data, const char* key, const char* value);
931 static bool _parseStyleAttr(void* data, const char* key, const char* value, bool style);
932
933
934 static bool _attrParseSvgNode(void* data, const char* key, const char* value)
935 {
936 SvgLoaderData* loader = (SvgLoaderData*)data;
937 SvgNode* node = loader->svgParse->node;
938 SvgDocNode* doc = &(node->node.doc);
939
940 if (!strcmp(key, "width")) {
941 doc->w = _toFloat(loader->svgParse, value, SvgParserLengthType::Horizontal);
942 if (strstr(value, "%") && !(doc->viewFlag & SvgViewFlag::Viewbox)) {
943 doc->viewFlag = (doc->viewFlag | SvgViewFlag::WidthInPercent);
944 } else {
945 doc->viewFlag = (doc->viewFlag | SvgViewFlag::Width);
946 }
947 } else if (!strcmp(key, "height")) {
948 doc->h = _toFloat(loader->svgParse, value, SvgParserLengthType::Vertical);
949 if (strstr(value, "%") && !(doc->viewFlag & SvgViewFlag::Viewbox)) {
950 doc->viewFlag = (doc->viewFlag | SvgViewFlag::HeightInPercent);
951 } else {
952 doc->viewFlag = (doc->viewFlag | SvgViewFlag::Height);
953 }
954 } else if (!strcmp(key, "viewBox")) {
955 if (_parseNumber(&value, nullptr, &doc->vx)) {
956 if (_parseNumber(&value, nullptr, &doc->vy)) {
957 if (_parseNumber(&value, nullptr, &doc->vw)) {
958 if (_parseNumber(&value, nullptr, &doc->vh)) {
959 doc->viewFlag = (doc->viewFlag | SvgViewFlag::Viewbox);
960 loader->svgParse->global.h = doc->vh;
961 }
962 loader->svgParse->global.w = doc->vw;
963 }
964 loader->svgParse->global.y = doc->vy;
965 }
966 loader->svgParse->global.x = doc->vx;
967 }
968 if ((doc->viewFlag & SvgViewFlag::Viewbox) && (doc->vw < 0.0f || doc->vh < 0.0f)) {
969 doc->viewFlag = (SvgViewFlag)((uint32_t)doc->viewFlag & ~(uint32_t)SvgViewFlag::Viewbox);
970 TVGLOG("SVG", "Negative values of the <viewBox> width and/or height - the attribute invalidated.");
971 }
972 if (!(doc->viewFlag & SvgViewFlag::Viewbox)) {
973 loader->svgParse->global.x = loader->svgParse->global.y = 0.0f;
974 loader->svgParse->global.w = loader->svgParse->global.h = 1.0f;
975 }
976 } else if (!strcmp(key, "preserveAspectRatio")) {
977 _parseAspectRatio(&value, &doc->align, &doc->meetOrSlice);
978 } else if (!strcmp(key, "style")) {
979 return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
980 #ifdef THORVG_LOG_ENABLED
981 } else if ((!strcmp(key, "x") || !strcmp(key, "y")) && fabsf(strToFloat(value, nullptr)) > FLOAT_EPSILON) {
982 TVGLOG("SVG", "Unsupported attributes used [Elements type: Svg][Attribute: %s][Value: %s]", key, value);
983 #endif
984 } else {
985 return _parseStyleAttr(loader, key, value, false);
986 }
987 return true;
988 }
989
990
991 //https://www.w3.org/TR/SVGTiny12/painting.html#SpecifyingPaint
992 static void _handlePaintAttr(SvgPaint* paint, const char* value)
993 {
994 if (!strcmp(value, "none")) {
995 //No paint property
996 paint->none = true;
997 return;
998 }
999 if (!strcmp(value, "currentColor")) {
1000 paint->curColor = true;
1001 paint->none = false;
1002 return;
1003 }
1004 if (_toColor(value, &paint->color.r, &paint->color.g, &paint->color.b, &paint->url)) paint->none = false;
1005 }
1006
1007
1008 static void _handleColorAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
1009 {
1010 SvgStyleProperty* style = node->style;
1011 if (_toColor(value, &style->color.r, &style->color.g, &style->color.b, nullptr)) {
1012 style->curColorSet = true;
1013 }
1014 }
1015
1016
1017 static void _handleFillAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
1018 {
1019 SvgStyleProperty* style = node->style;
1020 style->fill.flags = (style->fill.flags | SvgFillFlags::Paint);
1021 _handlePaintAttr(&style->fill.paint, value);
1022 }
1023
1024
1025 static void _handleStrokeAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
1026 {
1027 SvgStyleProperty* style = node->style;
1028 style->stroke.flags = (style->stroke.flags | SvgStrokeFlags::Paint);
1029 _handlePaintAttr(&style->stroke.paint, value);
1030 }
1031
1032
1033 static void _handleStrokeOpacityAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
1034 {
1035 node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::Opacity);
1036 node->style->stroke.opacity = _toOpacity(value);
1037 }
1038
1039 static void _handleStrokeDashArrayAttr(SvgLoaderData* loader, SvgNode* node, const char* value)
1040 {
1041 node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::Dash);
1042 _parseDashArray(loader, value, &node->style->stroke.dash);
1043 }
1044
1045 static void _handleStrokeDashOffsetAttr(SvgLoaderData* loader, SvgNode* node, const char* value)
1046 {
1047 node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::DashOffset);
1048 node->style->stroke.dash.offset = _toFloat(loader->svgParse, value, SvgParserLengthType::Horizontal);
1049 }
1050
1051 static void _handleStrokeWidthAttr(SvgLoaderData* loader, SvgNode* node, const char* value)
1052 {
1053 node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::Width);
1054 node->style->stroke.width = _toFloat(loader->svgParse, value, SvgParserLengthType::Diagonal);
1055 }
1056
1057
1058 static void _handleStrokeLineCapAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
1059 {
1060 node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::Cap);
1061 node->style->stroke.cap = _toLineCap(value);
1062 }
1063
1064
1065 static void _handleStrokeLineJoinAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
1066 {
1067 node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::Join);
1068 node->style->stroke.join = _toLineJoin(value);
1069 }
1070
1071 static void _handleStrokeMiterlimitAttr(SvgLoaderData* loader, SvgNode* node, const char* value)
1072 {
1073 char* end = nullptr;
1074 const float miterlimit = strToFloat(value, &end);
1075
1076 // https://www.w3.org/TR/SVG2/painting.html#LineJoin
1077 // - A negative value for stroke-miterlimit must be treated as an illegal value.
1078 if (miterlimit < 0.0f) {
1079 TVGERR("SVG", "A stroke-miterlimit change (%f <- %f) with a negative value is omitted.",
1080 node->style->stroke.miterlimit, miterlimit);
1081 return;
1082 }
1083
1084 node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::Miterlimit);
1085 node->style->stroke.miterlimit = miterlimit;
1086 }
1087
1088 static void _handleFillRuleAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
1089 {
1090 node->style->fill.flags = (node->style->fill.flags | SvgFillFlags::FillRule);
1091 node->style->fill.fillRule = _toFillRule(value);
1092 }
1093
1094
1095 static void _handleOpacityAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
1096 {
1097 node->style->flags = (node->style->flags | SvgStyleFlags::Opacity);
1098 node->style->opacity = _toOpacity(value);
1099 }
1100
1101
1102 static void _handleFillOpacityAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
1103 {
1104 node->style->fill.flags = (node->style->fill.flags | SvgFillFlags::Opacity);
1105 node->style->fill.opacity = _toOpacity(value);
1106 }
1107
1108
1109 static void _handleTransformAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
1110 {
1111 node->transform = _parseTransformationMatrix(value);
1112 }
1113
1114
1115 static void _handleClipPathAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
1116 {
1117 SvgStyleProperty* style = node->style;
1118 int len = strlen(value);
1119 if (len >= 3 && !strncmp(value, "url", 3)) {
1120 if (style->clipPath.url) free(style->clipPath.url);
1121 style->clipPath.url = _idFromUrl((const char*)(value + 3));
1122 }
1123 }
1124
1125
1126 static void _handleMaskAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
1127 {
1128 SvgStyleProperty* style = node->style;
1129 int len = strlen(value);
1130 if (len >= 3 && !strncmp(value, "url", 3)) {
1131 if (style->mask.url) free(style->mask.url);
1132 style->mask.url = _idFromUrl((const char*)(value + 3));
1133 }
1134 }
1135
1136
1137 static void _handleMaskTypeAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
1138 {
1139 node->node.mask.type = _toMaskType(value);
1140 }
1141
1142
1143 static void _handleDisplayAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
1144 {
1145 //TODO : The display attribute can have various values as well as "none".
1146 // The default is "inline" which means visible and "none" means invisible.
1147 // Depending on the type of node, additional functionality may be required.
1148 // refer to https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/display
1149 node->style->flags = (node->style->flags | SvgStyleFlags::Display);
1150 if (!strcmp(value, "none")) node->style->display = false;
1151 else node->style->display = true;
1152 }
1153
1154
1155 static void _handlePaintOrderAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
1156 {
1157 node->style->flags = (node->style->flags | SvgStyleFlags::PaintOrder);
1158 node->style->paintOrder = _toPaintOrder(value);
1159 }
1160
1161
1162 static void _handleCssClassAttr(SvgLoaderData* loader, SvgNode* node, const char* value)
1163 {
1164 auto cssClass = &node->style->cssClass;
1165
1166 if (*cssClass && value) free(*cssClass);
1167 *cssClass = _copyId(value);
1168
1169 bool cssClassFound = false;
1170
1171 //css styling: tag.name has higher priority than .name
1172 if (auto cssNode = cssFindStyleNode(loader->cssStyle, *cssClass, node->type)) {
1173 cssClassFound = true;
1174 cssCopyStyleAttr(node, cssNode);
1175 }
1176 if (auto cssNode = cssFindStyleNode(loader->cssStyle, *cssClass)) {
1177 cssClassFound = true;
1178 cssCopyStyleAttr(node, cssNode);
1179 }
1180
1181 if (!cssClassFound) loader->nodesToStyle.push({node, *cssClass});
1182 }
1183
1184
1185 typedef void (*styleMethod)(SvgLoaderData* loader, SvgNode* node, const char* value);
1186
1187 #define STYLE_DEF(Name, Name1, Flag) { #Name, sizeof(#Name), _handle##Name1##Attr, Flag }
1188
1189
1190 static constexpr struct
1191 {
1192 const char* tag;
1193 int sz;
1194 styleMethod tagHandler;
1195 SvgStyleFlags flag;
1196 } styleTags[] = {
1197 STYLE_DEF(color, Color, SvgStyleFlags::Color),
1198 STYLE_DEF(fill, Fill, SvgStyleFlags::Fill),
1199 STYLE_DEF(fill-rule, FillRule, SvgStyleFlags::FillRule),
1200 STYLE_DEF(fill-opacity, FillOpacity, SvgStyleFlags::FillOpacity),
1201 STYLE_DEF(opacity, Opacity, SvgStyleFlags::Opacity),
1202 STYLE_DEF(stroke, Stroke, SvgStyleFlags::Stroke),
1203 STYLE_DEF(stroke-width, StrokeWidth, SvgStyleFlags::StrokeWidth),
1204 STYLE_DEF(stroke-linejoin, StrokeLineJoin, SvgStyleFlags::StrokeLineJoin),
1205 STYLE_DEF(stroke-miterlimit, StrokeMiterlimit, SvgStyleFlags::StrokeMiterlimit),
1206 STYLE_DEF(stroke-linecap, StrokeLineCap, SvgStyleFlags::StrokeLineCap),
1207 STYLE_DEF(stroke-opacity, StrokeOpacity, SvgStyleFlags::StrokeOpacity),
1208 STYLE_DEF(stroke-dasharray, StrokeDashArray, SvgStyleFlags::StrokeDashArray),
1209 STYLE_DEF(stroke-dashoffset, StrokeDashOffset, SvgStyleFlags::StrokeDashOffset),
1210 STYLE_DEF(transform, Transform, SvgStyleFlags::Transform),
1211 STYLE_DEF(clip-path, ClipPath, SvgStyleFlags::ClipPath),
1212 STYLE_DEF(mask, Mask, SvgStyleFlags::Mask),
1213 STYLE_DEF(mask-type, MaskType, SvgStyleFlags::MaskType),
1214 STYLE_DEF(display, Display, SvgStyleFlags::Display),
1215 STYLE_DEF(paint-order, PaintOrder, SvgStyleFlags::PaintOrder)
1216 };
1217
1218
1219 static bool _parseStyleAttr(void* data, const char* key, const char* value, bool style)
1220 {
1221 SvgLoaderData* loader = (SvgLoaderData*)data;
1222 SvgNode* node = loader->svgParse->node;
1223 int sz;
1224 if (!key || !value) return false;
1225
1226 //Trim the white space
1227 key = _skipSpace(key, nullptr);
1228 value = _skipSpace(value, nullptr);
1229
1230 sz = strlen(key);
1231 for (unsigned int i = 0; i < sizeof(styleTags) / sizeof(styleTags[0]); i++) {
1232 if (styleTags[i].sz - 1 == sz && !strncmp(styleTags[i].tag, key, sz)) {
1233 bool importance = false;
1234 if (auto ptr = strstr(value, "!important")) {
1235 size_t size = ptr - value;
1236 while (size > 0 && isspace(value[size - 1])) {
1237 size--;
1238 }
1239 value = strDuplicate(value, size);
1240 importance = true;
1241 }
1242 if (style) {
1243 if (importance || !(node->style->flagsImportance & styleTags[i].flag)) {
1244 styleTags[i].tagHandler(loader, node, value);
1245 node->style->flags = (node->style->flags | styleTags[i].flag);
1246 }
1247 } else if (!(node->style->flags & styleTags[i].flag)) {
1248 styleTags[i].tagHandler(loader, node, value);
1249 }
1250 if (importance) {
1251 node->style->flagsImportance = (node->style->flags | styleTags[i].flag);
1252 free(const_cast<char*>(value));
1253 }
1254 return true;
1255 }
1256 }
1257
1258 return false;
1259 }
1260
1261
1262 static bool _parseStyleAttr(void* data, const char* key, const char* value)
1263 {
1264 return _parseStyleAttr(data, key, value, true);
1265 }
1266
1267
1268 /* parse g node
1269 * https://www.w3.org/TR/SVG/struct.html#Groups
1270 */
1271 static bool _attrParseGNode(void* data, const char* key, const char* value)
1272 {
1273 SvgLoaderData* loader = (SvgLoaderData*)data;
1274 SvgNode* node = loader->svgParse->node;
1275
1276 if (!strcmp(key, "style")) {
1277 return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
1278 } else if (!strcmp(key, "transform")) {
1279 node->transform = _parseTransformationMatrix(value);
1280 } else if (!strcmp(key, "id")) {
1281 if (node->id && value) free(node->id);
1282 node->id = _copyId(value);
1283 } else if (!strcmp(key, "class")) {
1284 _handleCssClassAttr(loader, node, value);
1285 } else if (!strcmp(key, "clip-path")) {
1286 _handleClipPathAttr(loader, node, value);
1287 } else if (!strcmp(key, "mask")) {
1288 _handleMaskAttr(loader, node, value);
1289 } else {
1290 return _parseStyleAttr(loader, key, value, false);
1291 }
1292 return true;
1293 }
1294
1295
1296 /* parse clipPath node
1297 * https://www.w3.org/TR/SVG/struct.html#Groups
1298 */
1299 static bool _attrParseClipPathNode(void* data, const char* key, const char* value)
1300 {
1301 SvgLoaderData* loader = (SvgLoaderData*)data;
1302 SvgNode* node = loader->svgParse->node;
1303 SvgClipNode* clip = &(node->node.clip);
1304
1305 if (!strcmp(key, "style")) {
1306 return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
1307 } else if (!strcmp(key, "transform")) {
1308 node->transform = _parseTransformationMatrix(value);
1309 } else if (!strcmp(key, "id")) {
1310 if (node->id && value) free(node->id);
1311 node->id = _copyId(value);
1312 } else if (!strcmp(key, "class")) {
1313 _handleCssClassAttr(loader, node, value);
1314 } else if (!strcmp(key, "clipPathUnits")) {
1315 if (!strcmp(value, "objectBoundingBox")) clip->userSpace = false;
1316 } else {
1317 return _parseStyleAttr(loader, key, value, false);
1318 }
1319 return true;
1320 }
1321
1322
1323 static bool _attrParseMaskNode(void* data, const char* key, const char* value)
1324 {
1325 SvgLoaderData* loader = (SvgLoaderData*)data;
1326 SvgNode* node = loader->svgParse->node;
1327 SvgMaskNode* mask = &(node->node.mask);
1328
1329 if (!strcmp(key, "style")) {
1330 return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
1331 } else if (!strcmp(key, "transform")) {
1332 node->transform = _parseTransformationMatrix(value);
1333 } else if (!strcmp(key, "id")) {
1334 if (node->id && value) free(node->id);
1335 node->id = _copyId(value);
1336 } else if (!strcmp(key, "class")) {
1337 _handleCssClassAttr(loader, node, value);
1338 } else if (!strcmp(key, "maskContentUnits")) {
1339 if (!strcmp(value, "objectBoundingBox")) mask->userSpace = false;
1340 } else if (!strcmp(key, "mask-type")) {
1341 mask->type = _toMaskType(value);
1342 } else {
1343 return _parseStyleAttr(loader, key, value, false);
1344 }
1345 return true;
1346 }
1347
1348
1349 static bool _attrParseCssStyleNode(void* data, const char* key, const char* value)
1350 {
1351 SvgLoaderData* loader = (SvgLoaderData*)data;
1352 SvgNode* node = loader->svgParse->node;
1353
1354 if (!strcmp(key, "id")) {
1355 if (node->id && value) free(node->id);
1356 node->id = _copyId(value);
1357 } else {
1358 return _parseStyleAttr(loader, key, value, false);
1359 }
1360 return true;
1361 }
1362
1363
1364 static bool _attrParseSymbolNode(void* data, const char* key, const char* value)
1365 {
1366 SvgLoaderData* loader = (SvgLoaderData*)data;
1367 SvgNode* node = loader->svgParse->node;
1368 SvgSymbolNode* symbol = &(node->node.symbol);
1369
1370 if (!strcmp(key, "viewBox")) {
1371 if (!_parseNumber(&value, nullptr, &symbol->vx) || !_parseNumber(&value, nullptr, &symbol->vy)) return false;
1372 if (!_parseNumber(&value, nullptr, &symbol->vw) || !_parseNumber(&value, nullptr, &symbol->vh)) return false;
1373 symbol->hasViewBox = true;
1374 } else if (!strcmp(key, "width")) {
1375 symbol->w = _toFloat(loader->svgParse, value, SvgParserLengthType::Horizontal);
1376 symbol->hasWidth = true;
1377 } else if (!strcmp(key, "height")) {
1378 symbol->h = _toFloat(loader->svgParse, value, SvgParserLengthType::Vertical);
1379 symbol->hasHeight = true;
1380 } else if (!strcmp(key, "preserveAspectRatio")) {
1381 _parseAspectRatio(&value, &symbol->align, &symbol->meetOrSlice);
1382 } else if (!strcmp(key, "overflow")) {
1383 if (!strcmp(value, "visible")) symbol->overflowVisible = true;
1384 } else {
1385 return _attrParseGNode(data, key, value);
1386 }
1387
1388 return true;
1389 }
1390
1391
1392 static SvgNode* _createNode(SvgNode* parent, SvgNodeType type)
1393 {
1394 SvgNode* node = (SvgNode*)calloc(1, sizeof(SvgNode));
1395
1396 if (!node) return nullptr;
1397
1398 //Default fill property
1399 node->style = (SvgStyleProperty*)calloc(1, sizeof(SvgStyleProperty));
1400
1401 if (!node->style) {
1402 free(node);
1403 return nullptr;
1404 }
1405
1406 //Update the default value of stroke and fill
1407 //https://www.w3.org/TR/SVGTiny12/painting.html#SpecifyingPaint
1408 node->style->fill.paint.none = false;
1409 //Default fill opacity is 1
1410 node->style->fill.opacity = 255;
1411 node->style->opacity = 255;
1412 //Default current color is not set
1413 node->style->fill.paint.curColor = false;
1414 node->style->curColorSet = false;
1415 //Default fill rule is nonzero
1416 node->style->fill.fillRule = FillRule::Winding;
1417
1418 //Default stroke is none
1419 node->style->stroke.paint.none = true;
1420 //Default stroke opacity is 1
1421 node->style->stroke.opacity = 255;
1422 //Default stroke current color is not set
1423 node->style->stroke.paint.curColor = false;
1424 //Default stroke width is 1
1425 node->style->stroke.width = 1;
1426 //Default line cap is butt
1427 node->style->stroke.cap = StrokeCap::Butt;
1428 //Default line join is miter
1429 node->style->stroke.join = StrokeJoin::Miter;
1430 node->style->stroke.miterlimit = 4.0f;
1431 node->style->stroke.scale = 1.0;
1432
1433 node->style->paintOrder = _toPaintOrder("fill stroke");
1434
1435 //Default display is true("inline").
1436 node->style->display = true;
1437
1438 node->parent = parent;
1439 node->type = type;
1440
1441 if (parent) parent->child.push(node);
1442 return node;
1443 }
1444
1445
1446 static SvgNode* _createDefsNode(TVG_UNUSED SvgLoaderData* loader, TVG_UNUSED SvgNode* parent, const char* buf, unsigned bufLength, TVG_UNUSED parseAttributes func)
1447 {
1448 if (loader->def && loader->doc->node.doc.defs) return loader->def;
1449 SvgNode* node = _createNode(nullptr, SvgNodeType::Defs);
1450
1451 loader->def = node;
1452 loader->doc->node.doc.defs = node;
1453 return node;
1454 }
1455
1456
1457 static SvgNode* _createGNode(TVG_UNUSED SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
1458 {
1459 loader->svgParse->node = _createNode(parent, SvgNodeType::G);
1460 if (!loader->svgParse->node) return nullptr;
1461
1462 func(buf, bufLength, _attrParseGNode, loader);
1463 return loader->svgParse->node;
1464 }
1465
1466
1467 static SvgNode* _createSvgNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
1468 {
1469 loader->svgParse->node = _createNode(parent, SvgNodeType::Doc);
1470 if (!loader->svgParse->node) return nullptr;
1471 SvgDocNode* doc = &(loader->svgParse->node->node.doc);
1472
1473 loader->svgParse->global.w = 1.0f;
1474 loader->svgParse->global.h = 1.0f;
1475
1476 doc->align = AspectRatioAlign::XMidYMid;
1477 doc->meetOrSlice = AspectRatioMeetOrSlice::Meet;
1478 doc->viewFlag = SvgViewFlag::None;
1479 func(buf, bufLength, _attrParseSvgNode, loader);
1480
1481 if (!(doc->viewFlag & SvgViewFlag::Viewbox)) {
1482 if (doc->viewFlag & SvgViewFlag::Width) {
1483 loader->svgParse->global.w = doc->w;
1484 }
1485 if (doc->viewFlag & SvgViewFlag::Height) {
1486 loader->svgParse->global.h = doc->h;
1487 }
1488 }
1489 return loader->svgParse->node;
1490 }
1491
1492
1493 static SvgNode* _createMaskNode(SvgLoaderData* loader, SvgNode* parent, TVG_UNUSED const char* buf, TVG_UNUSED unsigned bufLength, parseAttributes func)
1494 {
1495 loader->svgParse->node = _createNode(parent, SvgNodeType::Mask);
1496 if (!loader->svgParse->node) return nullptr;
1497
1498 loader->svgParse->node->node.mask.userSpace = true;
1499 loader->svgParse->node->node.mask.type = SvgMaskType::Luminance;
1500
1501 func(buf, bufLength, _attrParseMaskNode, loader);
1502
1503 return loader->svgParse->node;
1504 }
1505
1506
1507 static SvgNode* _createClipPathNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
1508 {
1509 loader->svgParse->node = _createNode(parent, SvgNodeType::ClipPath);
1510 if (!loader->svgParse->node) return nullptr;
1511
1512 loader->svgParse->node->style->display = false;
1513 loader->svgParse->node->node.clip.userSpace = true;
1514
1515 func(buf, bufLength, _attrParseClipPathNode, loader);
1516
1517 return loader->svgParse->node;
1518 }
1519
1520
1521 static SvgNode* _createCssStyleNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
1522 {
1523 loader->svgParse->node = _createNode(parent, SvgNodeType::CssStyle);
1524 if (!loader->svgParse->node) return nullptr;
1525
1526 func(buf, bufLength, _attrParseCssStyleNode, loader);
1527
1528 return loader->svgParse->node;
1529 }
1530
1531
1532 static SvgNode* _createSymbolNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
1533 {
1534 loader->svgParse->node = _createNode(parent, SvgNodeType::Symbol);
1535 if (!loader->svgParse->node) return nullptr;
1536
1537 loader->svgParse->node->node.symbol.align = AspectRatioAlign::XMidYMid;
1538 loader->svgParse->node->node.symbol.meetOrSlice = AspectRatioMeetOrSlice::Meet;
1539 loader->svgParse->node->node.symbol.overflowVisible = false;
1540
1541 loader->svgParse->node->node.symbol.hasViewBox = false;
1542 loader->svgParse->node->node.symbol.hasWidth = false;
1543 loader->svgParse->node->node.symbol.hasHeight = false;
1544 loader->svgParse->node->node.symbol.vx = 0.0f;
1545 loader->svgParse->node->node.symbol.vy = 0.0f;
1546
1547 func(buf, bufLength, _attrParseSymbolNode, loader);
1548
1549 return loader->svgParse->node;
1550 }
1551
1552
1553 static bool _attrParsePathNode(void* data, const char* key, const char* value)
1554 {
1555 SvgLoaderData* loader = (SvgLoaderData*)data;
1556 SvgNode* node = loader->svgParse->node;
1557 SvgPathNode* path = &(node->node.path);
1558
1559 if (!strcmp(key, "d")) {
1560 if (path->path) free(path->path);
1561 //Temporary: need to copy
1562 path->path = _copyId(value);
1563 } else if (!strcmp(key, "style")) {
1564 return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
1565 } else if (!strcmp(key, "clip-path")) {
1566 _handleClipPathAttr(loader, node, value);
1567 } else if (!strcmp(key, "mask")) {
1568 _handleMaskAttr(loader, node, value);
1569 } else if (!strcmp(key, "id")) {
1570 if (node->id && value) free(node->id);
1571 node->id = _copyId(value);
1572 } else if (!strcmp(key, "class")) {
1573 _handleCssClassAttr(loader, node, value);
1574 } else {
1575 return _parseStyleAttr(loader, key, value, false);
1576 }
1577 return true;
1578 }
1579
1580
1581 static SvgNode* _createPathNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
1582 {
1583 loader->svgParse->node = _createNode(parent, SvgNodeType::Path);
1584
1585 if (!loader->svgParse->node) return nullptr;
1586
1587 func(buf, bufLength, _attrParsePathNode, loader);
1588
1589 return loader->svgParse->node;
1590 }
1591
1592
1593 static constexpr struct
1594 {
1595 const char* tag;
1596 SvgParserLengthType type;
1597 int sz;
1598 size_t offset;
1599 } circleTags[] = {
1600 {"cx", SvgParserLengthType::Horizontal, sizeof("cx"), offsetof(SvgCircleNode, cx)},
1601 {"cy", SvgParserLengthType::Vertical, sizeof("cy"), offsetof(SvgCircleNode, cy)},
1602 {"r", SvgParserLengthType::Diagonal, sizeof("r"), offsetof(SvgCircleNode, r)}
1603 };
1604
1605
1606 /* parse the attributes for a circle element.
1607 * https://www.w3.org/TR/SVG/shapes.html#CircleElement
1608 */
1609 static bool _attrParseCircleNode(void* data, const char* key, const char* value)
1610 {
1611 SvgLoaderData* loader = (SvgLoaderData*)data;
1612 SvgNode* node = loader->svgParse->node;
1613 SvgCircleNode* circle = &(node->node.circle);
1614 unsigned char* array;
1615 int sz = strlen(key);
1616
1617 array = (unsigned char*)circle;
1618 for (unsigned int i = 0; i < sizeof(circleTags) / sizeof(circleTags[0]); i++) {
1619 if (circleTags[i].sz - 1 == sz && !strncmp(circleTags[i].tag, key, sz)) {
1620 *((float*)(array + circleTags[i].offset)) = _toFloat(loader->svgParse, value, circleTags[i].type);
1621 return true;
1622 }
1623 }
1624
1625 if (!strcmp(key, "style")) {
1626 return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
1627 } else if (!strcmp(key, "clip-path")) {
1628 _handleClipPathAttr(loader, node, value);
1629 } else if (!strcmp(key, "mask")) {
1630 _handleMaskAttr(loader, node, value);
1631 } else if (!strcmp(key, "id")) {
1632 if (node->id && value) free(node->id);
1633 node->id = _copyId(value);
1634 } else if (!strcmp(key, "class")) {
1635 _handleCssClassAttr(loader, node, value);
1636 } else {
1637 return _parseStyleAttr(loader, key, value, false);
1638 }
1639 return true;
1640 }
1641
1642
1643 static SvgNode* _createCircleNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
1644 {
1645 loader->svgParse->node = _createNode(parent, SvgNodeType::Circle);
1646
1647 if (!loader->svgParse->node) return nullptr;
1648
1649 func(buf, bufLength, _attrParseCircleNode, loader);
1650 return loader->svgParse->node;
1651 }
1652
1653
1654 static constexpr struct
1655 {
1656 const char* tag;
1657 SvgParserLengthType type;
1658 int sz;
1659 size_t offset;
1660 } ellipseTags[] = {
1661 {"cx", SvgParserLengthType::Horizontal, sizeof("cx"), offsetof(SvgEllipseNode, cx)},
1662 {"cy", SvgParserLengthType::Vertical, sizeof("cy"), offsetof(SvgEllipseNode, cy)},
1663 {"rx", SvgParserLengthType::Horizontal, sizeof("rx"), offsetof(SvgEllipseNode, rx)},
1664 {"ry", SvgParserLengthType::Vertical, sizeof("ry"), offsetof(SvgEllipseNode, ry)}
1665 };
1666
1667
1668 /* parse the attributes for an ellipse element.
1669 * https://www.w3.org/TR/SVG/shapes.html#EllipseElement
1670 */
1671 static bool _attrParseEllipseNode(void* data, const char* key, const char* value)
1672 {
1673 SvgLoaderData* loader = (SvgLoaderData*)data;
1674 SvgNode* node = loader->svgParse->node;
1675 SvgEllipseNode* ellipse = &(node->node.ellipse);
1676 unsigned char* array;
1677 int sz = strlen(key);
1678
1679 array = (unsigned char*)ellipse;
1680 for (unsigned int i = 0; i < sizeof(ellipseTags) / sizeof(ellipseTags[0]); i++) {
1681 if (ellipseTags[i].sz - 1 == sz && !strncmp(ellipseTags[i].tag, key, sz)) {
1682 *((float*)(array + ellipseTags[i].offset)) = _toFloat(loader->svgParse, value, ellipseTags[i].type);
1683 return true;
1684 }
1685 }
1686
1687 if (!strcmp(key, "id")) {
1688 if (node->id && value) free(node->id);
1689 node->id = _copyId(value);
1690 } else if (!strcmp(key, "class")) {
1691 _handleCssClassAttr(loader, node, value);
1692 } else if (!strcmp(key, "style")) {
1693 return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
1694 } else if (!strcmp(key, "clip-path")) {
1695 _handleClipPathAttr(loader, node, value);
1696 } else if (!strcmp(key, "mask")) {
1697 _handleMaskAttr(loader, node, value);
1698 } else {
1699 return _parseStyleAttr(loader, key, value, false);
1700 }
1701 return true;
1702 }
1703
1704
1705 static SvgNode* _createEllipseNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
1706 {
1707 loader->svgParse->node = _createNode(parent, SvgNodeType::Ellipse);
1708
1709 if (!loader->svgParse->node) return nullptr;
1710
1711 func(buf, bufLength, _attrParseEllipseNode, loader);
1712 return loader->svgParse->node;
1713 }
1714
1715
1716 static bool _attrParsePolygonPoints(const char* str, SvgPolygonNode* polygon)
1717 {
1718 float num_x, num_y;
1719 while (_parseNumber(&str, nullptr, &num_x) && _parseNumber(&str, nullptr, &num_y)) {
1720 polygon->pts.push(num_x);
1721 polygon->pts.push(num_y);
1722 }
1723 return true;
1724 }
1725
1726
1727 /* parse the attributes for a polygon element.
1728 * https://www.w3.org/TR/SVG/shapes.html#PolylineElement
1729 */
1730 static bool _attrParsePolygonNode(void* data, const char* key, const char* value)
1731 {
1732 SvgLoaderData* loader = (SvgLoaderData*)data;
1733 SvgNode* node = loader->svgParse->node;
1734 SvgPolygonNode* polygon = nullptr;
1735
1736 if (node->type == SvgNodeType::Polygon) polygon = &(node->node.polygon);
1737 else polygon = &(node->node.polyline);
1738
1739 if (!strcmp(key, "points")) {
1740 return _attrParsePolygonPoints(value, polygon);
1741 } else if (!strcmp(key, "style")) {
1742 return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
1743 } else if (!strcmp(key, "clip-path")) {
1744 _handleClipPathAttr(loader, node, value);
1745 } else if (!strcmp(key, "mask")) {
1746 _handleMaskAttr(loader, node, value);
1747 } else if (!strcmp(key, "id")) {
1748 if (node->id && value) free(node->id);
1749 node->id = _copyId(value);
1750 } else if (!strcmp(key, "class")) {
1751 _handleCssClassAttr(loader, node, value);
1752 } else {
1753 return _parseStyleAttr(loader, key, value, false);
1754 }
1755 return true;
1756 }
1757
1758
1759 static SvgNode* _createPolygonNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
1760 {
1761 loader->svgParse->node = _createNode(parent, SvgNodeType::Polygon);
1762
1763 if (!loader->svgParse->node) return nullptr;
1764
1765 func(buf, bufLength, _attrParsePolygonNode, loader);
1766 return loader->svgParse->node;
1767 }
1768
1769
1770 static SvgNode* _createPolylineNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
1771 {
1772 loader->svgParse->node = _createNode(parent, SvgNodeType::Polyline);
1773
1774 if (!loader->svgParse->node) return nullptr;
1775
1776 func(buf, bufLength, _attrParsePolygonNode, loader);
1777 return loader->svgParse->node;
1778 }
1779
1780 static constexpr struct
1781 {
1782 const char* tag;
1783 SvgParserLengthType type;
1784 int sz;
1785 size_t offset;
1786 } rectTags[] = {
1787 {"x", SvgParserLengthType::Horizontal, sizeof("x"), offsetof(SvgRectNode, x)},
1788 {"y", SvgParserLengthType::Vertical, sizeof("y"), offsetof(SvgRectNode, y)},
1789 {"width", SvgParserLengthType::Horizontal, sizeof("width"), offsetof(SvgRectNode, w)},
1790 {"height", SvgParserLengthType::Vertical, sizeof("height"), offsetof(SvgRectNode, h)},
1791 {"rx", SvgParserLengthType::Horizontal, sizeof("rx"), offsetof(SvgRectNode, rx)},
1792 {"ry", SvgParserLengthType::Vertical, sizeof("ry"), offsetof(SvgRectNode, ry)}
1793 };
1794
1795
1796 /* parse the attributes for a rect element.
1797 * https://www.w3.org/TR/SVG/shapes.html#RectElement
1798 */
1799 static bool _attrParseRectNode(void* data, const char* key, const char* value)
1800 {
1801 SvgLoaderData* loader = (SvgLoaderData*)data;
1802 SvgNode* node = loader->svgParse->node;
1803 SvgRectNode* rect = &(node->node.rect);
1804 unsigned char* array;
1805 bool ret = true;
1806 int sz = strlen(key);
1807
1808 array = (unsigned char*)rect;
1809 for (unsigned int i = 0; i < sizeof(rectTags) / sizeof(rectTags[0]); i++) {
1810 if (rectTags[i].sz - 1 == sz && !strncmp(rectTags[i].tag, key, sz)) {
1811 *((float*)(array + rectTags[i].offset)) = _toFloat(loader->svgParse, value, rectTags[i].type);
1812
1813 //Case if only rx or ry is declared
1814 if (!strncmp(rectTags[i].tag, "rx", sz)) rect->hasRx = true;
1815 if (!strncmp(rectTags[i].tag, "ry", sz)) rect->hasRy = true;
1816
1817 if ((rect->rx >= FLOAT_EPSILON) && (rect->ry < FLOAT_EPSILON) && rect->hasRx && !rect->hasRy) rect->ry = rect->rx;
1818 if ((rect->ry >= FLOAT_EPSILON) && (rect->rx < FLOAT_EPSILON) && !rect->hasRx && rect->hasRy) rect->rx = rect->ry;
1819 return ret;
1820 }
1821 }
1822
1823 if (!strcmp(key, "id")) {
1824 if (node->id && value) free(node->id);
1825 node->id = _copyId(value);
1826 } else if (!strcmp(key, "class")) {
1827 _handleCssClassAttr(loader, node, value);
1828 } else if (!strcmp(key, "style")) {
1829 ret = simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
1830 } else if (!strcmp(key, "clip-path")) {
1831 _handleClipPathAttr(loader, node, value);
1832 } else if (!strcmp(key, "mask")) {
1833 _handleMaskAttr(loader, node, value);
1834 } else {
1835 ret = _parseStyleAttr(loader, key, value, false);
1836 }
1837
1838 return ret;
1839 }
1840
1841
1842 static SvgNode* _createRectNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
1843 {
1844 loader->svgParse->node = _createNode(parent, SvgNodeType::Rect);
1845
1846 if (!loader->svgParse->node) return nullptr;
1847
1848 loader->svgParse->node->node.rect.hasRx = loader->svgParse->node->node.rect.hasRy = false;
1849
1850 func(buf, bufLength, _attrParseRectNode, loader);
1851 return loader->svgParse->node;
1852 }
1853
1854
1855 static constexpr struct
1856 {
1857 const char* tag;
1858 SvgParserLengthType type;
1859 int sz;
1860 size_t offset;
1861 } lineTags[] = {
1862 {"x1", SvgParserLengthType::Horizontal, sizeof("x1"), offsetof(SvgLineNode, x1)},
1863 {"y1", SvgParserLengthType::Vertical, sizeof("y1"), offsetof(SvgLineNode, y1)},
1864 {"x2", SvgParserLengthType::Horizontal, sizeof("x2"), offsetof(SvgLineNode, x2)},
1865 {"y2", SvgParserLengthType::Vertical, sizeof("y2"), offsetof(SvgLineNode, y2)}
1866 };
1867
1868
1869 /* parse the attributes for a line element.
1870 * https://www.w3.org/TR/SVG/shapes.html#LineElement
1871 */
1872 static bool _attrParseLineNode(void* data, const char* key, const char* value)
1873 {
1874 SvgLoaderData* loader = (SvgLoaderData*)data;
1875 SvgNode* node = loader->svgParse->node;
1876 SvgLineNode* line = &(node->node.line);
1877 unsigned char* array;
1878 int sz = strlen(key);
1879
1880 array = (unsigned char*)line;
1881 for (unsigned int i = 0; i < sizeof(lineTags) / sizeof(lineTags[0]); i++) {
1882 if (lineTags[i].sz - 1 == sz && !strncmp(lineTags[i].tag, key, sz)) {
1883 *((float*)(array + lineTags[i].offset)) = _toFloat(loader->svgParse, value, lineTags[i].type);
1884 return true;
1885 }
1886 }
1887
1888 if (!strcmp(key, "id")) {
1889 if (node->id && value) free(node->id);
1890 node->id = _copyId(value);
1891 } else if (!strcmp(key, "class")) {
1892 _handleCssClassAttr(loader, node, value);
1893 } else if (!strcmp(key, "style")) {
1894 return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
1895 } else if (!strcmp(key, "clip-path")) {
1896 _handleClipPathAttr(loader, node, value);
1897 } else if (!strcmp(key, "mask")) {
1898 _handleMaskAttr(loader, node, value);
1899 } else {
1900 return _parseStyleAttr(loader, key, value, false);
1901 }
1902 return true;
1903 }
1904
1905
1906 static SvgNode* _createLineNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
1907 {
1908 loader->svgParse->node = _createNode(parent, SvgNodeType::Line);
1909
1910 if (!loader->svgParse->node) return nullptr;
1911
1912 func(buf, bufLength, _attrParseLineNode, loader);
1913 return loader->svgParse->node;
1914 }
1915
1916
1917 static char* _idFromHref(const char* href)
1918 {
1919 href = _skipSpace(href, nullptr);
1920 if ((*href) == '#') href++;
1921 return strdup(href);
1922 }
1923
1924
1925 static constexpr struct
1926 {
1927 const char* tag;
1928 SvgParserLengthType type;
1929 int sz;
1930 size_t offset;
1931 } imageTags[] = {
1932 {"x", SvgParserLengthType::Horizontal, sizeof("x"), offsetof(SvgRectNode, x)},
1933 {"y", SvgParserLengthType::Vertical, sizeof("y"), offsetof(SvgRectNode, y)},
1934 {"width", SvgParserLengthType::Horizontal, sizeof("width"), offsetof(SvgRectNode, w)},
1935 {"height", SvgParserLengthType::Vertical, sizeof("height"), offsetof(SvgRectNode, h)},
1936 };
1937
1938
1939 /* parse the attributes for a image element.
1940 * https://www.w3.org/TR/SVG/embedded.html#ImageElement
1941 */
1942 static bool _attrParseImageNode(void* data, const char* key, const char* value)
1943 {
1944 SvgLoaderData* loader = (SvgLoaderData*)data;
1945 SvgNode* node = loader->svgParse->node;
1946 SvgImageNode* image = &(node->node.image);
1947 unsigned char* array;
1948 int sz = strlen(key);
1949
1950 array = (unsigned char*)image;
1951 for (unsigned int i = 0; i < sizeof(imageTags) / sizeof(imageTags[0]); i++) {
1952 if (imageTags[i].sz - 1 == sz && !strncmp(imageTags[i].tag, key, sz)) {
1953 *((float*)(array + imageTags[i].offset)) = _toFloat(loader->svgParse, value, imageTags[i].type);
1954 return true;
1955 }
1956 }
1957
1958 if (!strcmp(key, "href") || !strcmp(key, "xlink:href")) {
1959 if (image->href && value) free(image->href);
1960 image->href = _idFromHref(value);
1961 } else if (!strcmp(key, "id")) {
1962 if (node->id && value) free(node->id);
1963 node->id = _copyId(value);
1964 } else if (!strcmp(key, "class")) {
1965 _handleCssClassAttr(loader, node, value);
1966 } else if (!strcmp(key, "style")) {
1967 return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
1968 } else if (!strcmp(key, "clip-path")) {
1969 _handleClipPathAttr(loader, node, value);
1970 } else if (!strcmp(key, "mask")) {
1971 _handleMaskAttr(loader, node, value);
1972 } else if (!strcmp(key, "transform")) {
1973 node->transform = _parseTransformationMatrix(value);
1974 } else {
1975 return _parseStyleAttr(loader, key, value);
1976 }
1977 return true;
1978 }
1979
1980
1981 static SvgNode* _createImageNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
1982 {
1983 loader->svgParse->node = _createNode(parent, SvgNodeType::Image);
1984
1985 if (!loader->svgParse->node) return nullptr;
1986
1987 func(buf, bufLength, _attrParseImageNode, loader);
1988 return loader->svgParse->node;
1989 }
1990
1991
1992 static char* _unquote(const char* str)
1993 {
1994 auto len = str ? strlen(str) : 0;
1995 if (len >= 2 && str[0] == '\'' && str[len - 1] == '\'') return strDuplicate(str + 1, len - 2);
1996 return strdup(str);
1997 }
1998
1999
2000 static bool _attrParseFontFace(void* data, const char* key, const char* value)
2001 {
2002 if (!key || !value) return false;
2003
2004 key = _skipSpace(key, nullptr);
2005 value = _skipSpace(value, nullptr);
2006
2007 auto loader = (SvgLoaderData*)data;
2008 auto& font = loader->fonts.last();
2009
2010 if (!strcmp(key, "font-family")) {
2011 if (font.name) free(font.name);
2012 font.name = _unquote(value);
2013 } else if (!strcmp(key, "src")) {
2014 font.srcLen = _srcFromUrl(value, font.src);
2015 }
2016
2017 return true;
2018 }
2019
2020
2021 static void _createFontFace(SvgLoaderData* loader, const char* buf, unsigned bufLength, parseAttributes func)
2022 {
2023 loader->fonts.push(FontFace());
2024 func(buf, bufLength, _attrParseFontFace, loader);
2025 }
2026
2027
2028 static SvgNode* _getDefsNode(SvgNode* node)
2029 {
2030 if (!node) return nullptr;
2031
2032 while (node->parent != nullptr) {
2033 node = node->parent;
2034 }
2035
2036 if (node->type == SvgNodeType::Doc) return node->node.doc.defs;
2037 if (node->type == SvgNodeType::Defs) return node;
2038
2039 return nullptr;
2040 }
2041
2042
2043 static SvgNode* _findNodeById(SvgNode *node, const char* id)
2044 {
2045 if (!node) return nullptr;
2046
2047 SvgNode* result = nullptr;
2048 if (node->id && !strcmp(node->id, id)) return node;
2049
2050 if (node->child.count > 0) {
2051 auto child = node->child.data;
2052 for (uint32_t i = 0; i < node->child.count; ++i, ++child) {
2053 result = _findNodeById(*child, id);
2054 if (result) break;
2055 }
2056 }
2057 return result;
2058 }
2059
2060
2061 static SvgNode* _findParentById(SvgNode* node, char* id, SvgNode* doc)
2062 {
2063 SvgNode *parent = node->parent;
2064 while (parent != nullptr && parent != doc) {
2065 if (parent->id && !strcmp(parent->id, id)) {
2066 return parent;
2067 }
2068 parent = parent->parent;
2069 }
2070 return nullptr;
2071 }
2072
2073
2074 static bool _checkPostponed(SvgNode* node, SvgNode* cloneNode, int depth)
2075 {
2076 if (node == cloneNode) return true;
2077
2078 if (depth == 512) {
2079 TVGERR("SVG", "Infinite recursive call - stopped after %d calls! Svg file may be incorrectly formatted.", depth);
2080 return false;
2081 }
2082
2083 for (uint32_t i = 0; i < node->child.count; ++i) {
2084 if (_checkPostponed(node->child[i], cloneNode, depth + 1)) return true;
2085 }
2086
2087 return false;
2088 }
2089
2090
2091 static constexpr struct
2092 {
2093 const char* tag;
2094 SvgParserLengthType type;
2095 int sz;
2096 size_t offset;
2097 } useTags[] = {
2098 {"x", SvgParserLengthType::Horizontal, sizeof("x"), offsetof(SvgUseNode, x)},
2099 {"y", SvgParserLengthType::Vertical, sizeof("y"), offsetof(SvgUseNode, y)},
2100 {"width", SvgParserLengthType::Horizontal, sizeof("width"), offsetof(SvgUseNode, w)},
2101 {"height", SvgParserLengthType::Vertical, sizeof("height"), offsetof(SvgUseNode, h)}
2102 };
2103
2104
2105 static void _cloneNode(SvgNode* from, SvgNode* parent, int depth);
2106 static bool _attrParseUseNode(void* data, const char* key, const char* value)
2107 {
2108 SvgLoaderData* loader = (SvgLoaderData*)data;
2109 SvgNode *defs, *nodeFrom, *node = loader->svgParse->node;
2110 char* id;
2111
2112 SvgUseNode* use = &(node->node.use);
2113 int sz = strlen(key);
2114 unsigned char* array = (unsigned char*)use;
2115 for (unsigned int i = 0; i < sizeof(useTags) / sizeof(useTags[0]); i++) {
2116 if (useTags[i].sz - 1 == sz && !strncmp(useTags[i].tag, key, sz)) {
2117 *((float*)(array + useTags[i].offset)) = _toFloat(loader->svgParse, value, useTags[i].type);
2118
2119 if (useTags[i].offset == offsetof(SvgUseNode, w)) use->isWidthSet = true;
2120 else if (useTags[i].offset == offsetof(SvgUseNode, h)) use->isHeightSet = true;
2121
2122 return true;
2123 }
2124 }
2125
2126 if (!strcmp(key, "href") || !strcmp(key, "xlink:href")) {
2127 id = _idFromHref(value);
2128 defs = _getDefsNode(node);
2129 nodeFrom = _findNodeById(defs, id);
2130 if (nodeFrom) {
2131 if (!_findParentById(node, id, loader->doc)) {
2132 //Check if none of nodeFrom's children are in the cloneNodes list
2133 auto postpone = false;
2134 for (auto pair = loader->cloneNodes.head; pair; pair = pair->next) {
2135 if (_checkPostponed(nodeFrom, pair->node, 1)) {
2136 postpone = true;
2137 loader->cloneNodes.back(new((SvgNodeIdPair*)malloc(sizeof(SvgNodeIdPair))) SvgNodeIdPair(node, id));
2138 break;
2139 }
2140 }
2141 //None of the children of nodeFrom are on the cloneNodes list, so it can be cloned immediately
2142 if (!postpone) {
2143 _cloneNode(nodeFrom, node, 0);
2144 if (nodeFrom->type == SvgNodeType::Symbol) use->symbol = nodeFrom;
2145 free(id);
2146 }
2147 } else {
2148 TVGLOG("SVG", "%s is ancestor element. This reference is invalid.", id);
2149 free(id);
2150 }
2151 } else {
2152 //some svg export software include <defs> element at the end of the file
2153 //if so the 'from' element won't be found now and we have to repeat finding
2154 //after the whole file is parsed
2155 loader->cloneNodes.back(new((SvgNodeIdPair*)malloc(sizeof(SvgNodeIdPair))) SvgNodeIdPair(node, id));
2156 }
2157 } else {
2158 return _attrParseGNode(data, key, value);
2159 }
2160 return true;
2161 }
2162
2163
2164 static SvgNode* _createUseNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
2165 {
2166 loader->svgParse->node = _createNode(parent, SvgNodeType::Use);
2167
2168 if (!loader->svgParse->node) return nullptr;
2169
2170 loader->svgParse->node->node.use.isWidthSet = false;
2171 loader->svgParse->node->node.use.isHeightSet = false;
2172
2173 func(buf, bufLength, _attrParseUseNode, loader);
2174 return loader->svgParse->node;
2175 }
2176
2177
2178 static constexpr struct
2179 {
2180 const char* tag;
2181 SvgParserLengthType type;
2182 int sz;
2183 size_t offset;
2184 } textTags[] = {
2185 {"x", SvgParserLengthType::Horizontal, sizeof("x"), offsetof(SvgTextNode, x)},
2186 {"y", SvgParserLengthType::Vertical, sizeof("y"), offsetof(SvgTextNode, y)},
2187 {"font-size", SvgParserLengthType::Vertical, sizeof("font-size"), offsetof(SvgTextNode, fontSize)}
2188 };
2189
2190
2191 static bool _attrParseTextNode(void* data, const char* key, const char* value)
2192 {
2193 SvgLoaderData* loader = (SvgLoaderData*)data;
2194 SvgNode* node = loader->svgParse->node;
2195 SvgTextNode* text = &(node->node.text);
2196
2197 unsigned char* array;
2198 int sz = strlen(key);
2199
2200 array = (unsigned char*)text;
2201 for (unsigned int i = 0; i < sizeof(textTags) / sizeof(textTags[0]); i++) {
2202 if (textTags[i].sz - 1 == sz && !strncmp(textTags[i].tag, key, sz)) {
2203 *((float*)(array + textTags[i].offset)) = _toFloat(loader->svgParse, value, textTags[i].type);
2204 return true;
2205 }
2206 }
2207
2208 if (!strcmp(key, "font-family")) {
2209 if (text->fontFamily && value) free(text->fontFamily);
2210 text->fontFamily = strdup(value);
2211 } else if (!strcmp(key, "style")) {
2212 return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
2213 } else if (!strcmp(key, "clip-path")) {
2214 _handleClipPathAttr(loader, node, value);
2215 } else if (!strcmp(key, "mask")) {
2216 _handleMaskAttr(loader, node, value);
2217 } else if (!strcmp(key, "id")) {
2218 if (node->id && value) free(node->id);
2219 node->id = _copyId(value);
2220 } else if (!strcmp(key, "class")) {
2221 _handleCssClassAttr(loader, node, value);
2222 } else {
2223 return _parseStyleAttr(loader, key, value, false);
2224 }
2225 return true;
2226 }
2227
2228
2229 static SvgNode* _createTextNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
2230 {
2231 loader->svgParse->node = _createNode(parent, SvgNodeType::Text);
2232 if (!loader->svgParse->node) return nullptr;
2233
2234 //TODO: support the def font and size as used in a system?
2235 loader->svgParse->node->node.text.fontSize = 10.0f;
2236 loader->svgParse->node->node.text.fontFamily = nullptr;
2237 loader->svgParse->node->node.text.text = nullptr;
2238
2239 func(buf, bufLength, _attrParseTextNode, loader);
2240
2241 return loader->svgParse->node;
2242 }
2243
2244
2245 static constexpr struct
2246 {
2247 const char* tag;
2248 int sz;
2249 FactoryMethod tagHandler;
2250 } graphicsTags[] = {
2251 {"use", sizeof("use"), _createUseNode},
2252 {"circle", sizeof("circle"), _createCircleNode},
2253 {"ellipse", sizeof("ellipse"), _createEllipseNode},
2254 {"path", sizeof("path"), _createPathNode},
2255 {"polygon", sizeof("polygon"), _createPolygonNode},
2256 {"rect", sizeof("rect"), _createRectNode},
2257 {"polyline", sizeof("polyline"), _createPolylineNode},
2258 {"line", sizeof("line"), _createLineNode},
2259 {"image", sizeof("image"), _createImageNode},
2260 {"text", sizeof("text"), _createTextNode}
2261 };
2262
2263
2264 static constexpr struct
2265 {
2266 const char* tag;
2267 int sz;
2268 FactoryMethod tagHandler;
2269 } groupTags[] = {
2270 {"defs", sizeof("defs"), _createDefsNode},
2271 {"g", sizeof("g"), _createGNode},
2272 {"svg", sizeof("svg"), _createSvgNode},
2273 {"mask", sizeof("mask"), _createMaskNode},
2274 {"clipPath", sizeof("clipPath"), _createClipPathNode},
2275 {"style", sizeof("style"), _createCssStyleNode},
2276 {"symbol", sizeof("symbol"), _createSymbolNode}
2277 };
2278
2279
2280 #define FIND_FACTORY(Short_Name, Tags_Array) \
2281 static FactoryMethod \
2282 _find##Short_Name##Factory(const char* name) \
2283 { \
2284 unsigned int i; \
2285 int sz = strlen(name); \
2286 \
2287 for (i = 0; i < sizeof(Tags_Array) / sizeof(Tags_Array[0]); i++) { \
2288 if (Tags_Array[i].sz - 1 == sz && !strncmp(Tags_Array[i].tag, name, sz)) { \
2289 return Tags_Array[i].tagHandler; \
2290 } \
2291 } \
2292 return nullptr; \
2293 }
2294
2295 FIND_FACTORY(Group, groupTags)
2296 FIND_FACTORY(Graphics, graphicsTags)
2297
2298
2299 FillSpread _parseSpreadValue(const char* value)
2300 {
2301 auto spread = FillSpread::Pad;
2302
2303 if (!strcmp(value, "reflect")) {
2304 spread = FillSpread::Reflect;
2305 } else if (!strcmp(value, "repeat")) {
2306 spread = FillSpread::Repeat;
2307 }
2308
2309 return spread;
2310 }
2311
2312
2313 static void _handleRadialCxAttr(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value)
2314 {
2315 radial->cx = _gradientToFloat(loader->svgParse, value, radial->isCxPercentage);
2316 if (!loader->svgParse->gradient.parsedFx) {
2317 radial->fx = radial->cx;
2318 radial->isFxPercentage = radial->isCxPercentage;
2319 }
2320 }
2321
2322
2323 static void _handleRadialCyAttr(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value)
2324 {
2325 radial->cy = _gradientToFloat(loader->svgParse, value, radial->isCyPercentage);
2326 if (!loader->svgParse->gradient.parsedFy) {
2327 radial->fy = radial->cy;
2328 radial->isFyPercentage = radial->isCyPercentage;
2329 }
2330 }
2331
2332
2333 static void _handleRadialFxAttr(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value)
2334 {
2335 radial->fx = _gradientToFloat(loader->svgParse, value, radial->isFxPercentage);
2336 loader->svgParse->gradient.parsedFx = true;
2337 }
2338
2339
2340 static void _handleRadialFyAttr(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value)
2341 {
2342 radial->fy = _gradientToFloat(loader->svgParse, value, radial->isFyPercentage);
2343 loader->svgParse->gradient.parsedFy = true;
2344 }
2345
2346
2347 static void _handleRadialFrAttr(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value)
2348 {
2349 radial->fr = _gradientToFloat(loader->svgParse, value, radial->isFrPercentage);
2350 }
2351
2352
2353 static void _handleRadialRAttr(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value)
2354 {
2355 radial->r = _gradientToFloat(loader->svgParse, value, radial->isRPercentage);
2356 }
2357
2358
2359 static void _recalcRadialCxAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
2360 {
2361 if (userSpace && !radial->isCxPercentage) radial->cx = radial->cx / loader->svgParse->global.w;
2362 }
2363
2364
2365 static void _recalcRadialCyAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
2366 {
2367 if (userSpace && !radial->isCyPercentage) radial->cy = radial->cy / loader->svgParse->global.h;
2368 }
2369
2370
2371 static void _recalcRadialFxAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
2372 {
2373 if (userSpace && !radial->isFxPercentage) radial->fx = radial->fx / loader->svgParse->global.w;
2374 }
2375
2376
2377 static void _recalcRadialFyAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
2378 {
2379 if (userSpace && !radial->isFyPercentage) radial->fy = radial->fy / loader->svgParse->global.h;
2380 }
2381
2382
2383 static void _recalcRadialFrAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
2384 {
2385 // scaling factor based on the Units paragraph from : https://www.w3.org/TR/2015/WD-SVG2-20150915/coords.html
2386 if (userSpace && !radial->isFrPercentage) radial->fr = radial->fr / (sqrtf(powf(loader->svgParse->global.h, 2) + powf(loader->svgParse->global.w, 2)) / sqrtf(2.0));
2387 }
2388
2389
2390 static void _recalcRadialRAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
2391 {
2392 // scaling factor based on the Units paragraph from : https://www.w3.org/TR/2015/WD-SVG2-20150915/coords.html
2393 if (userSpace && !radial->isRPercentage) radial->r = radial->r / (sqrtf(powf(loader->svgParse->global.h, 2) + powf(loader->svgParse->global.w, 2)) / sqrtf(2.0));
2394 }
2395
2396
2397 static void _recalcInheritedRadialCxAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
2398 {
2399 if (!radial->isCxPercentage) {
2400 if (userSpace) radial->cx /= loader->svgParse->global.w;
2401 else radial->cx *= loader->svgParse->global.w;
2402 }
2403 }
2404
2405
2406 static void _recalcInheritedRadialCyAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
2407 {
2408 if (!radial->isCyPercentage) {
2409 if (userSpace) radial->cy /= loader->svgParse->global.h;
2410 else radial->cy *= loader->svgParse->global.h;
2411 }
2412 }
2413
2414
2415 static void _recalcInheritedRadialFxAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
2416 {
2417 if (!radial->isFxPercentage) {
2418 if (userSpace) radial->fx /= loader->svgParse->global.w;
2419 else radial->fx *= loader->svgParse->global.w;
2420 }
2421 }
2422
2423
2424 static void _recalcInheritedRadialFyAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
2425 {
2426 if (!radial->isFyPercentage) {
2427 if (userSpace) radial->fy /= loader->svgParse->global.h;
2428 else radial->fy *= loader->svgParse->global.h;
2429 }
2430 }
2431
2432
2433 static void _recalcInheritedRadialFrAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
2434 {
2435 if (!radial->isFrPercentage) {
2436 if (userSpace) radial->fr /= sqrtf(powf(loader->svgParse->global.h, 2) + powf(loader->svgParse->global.w, 2)) / sqrtf(2.0);
2437 else radial->fr *= sqrtf(powf(loader->svgParse->global.h, 2) + powf(loader->svgParse->global.w, 2)) / sqrtf(2.0);
2438 }
2439 }
2440
2441
2442 static void _recalcInheritedRadialRAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
2443 {
2444 if (!radial->isRPercentage) {
2445 if (userSpace) radial->r /= sqrtf(powf(loader->svgParse->global.h, 2) + powf(loader->svgParse->global.w, 2)) / sqrtf(2.0);
2446 else radial->r *= sqrtf(powf(loader->svgParse->global.h, 2) + powf(loader->svgParse->global.w, 2)) / sqrtf(2.0);
2447 }
2448 }
2449
2450
2451 static void _inheritRadialCxAttr(SvgStyleGradient* to, SvgStyleGradient* from)
2452 {
2453 to->radial->cx = from->radial->cx;
2454 to->radial->isCxPercentage = from->radial->isCxPercentage;
2455 to->flags = (to->flags | SvgGradientFlags::Cx);
2456 }
2457
2458
2459 static void _inheritRadialCyAttr(SvgStyleGradient* to, SvgStyleGradient* from)
2460 {
2461 to->radial->cy = from->radial->cy;
2462 to->radial->isCyPercentage = from->radial->isCyPercentage;
2463 to->flags = (to->flags | SvgGradientFlags::Cy);
2464 }
2465
2466
2467 static void _inheritRadialFxAttr(SvgStyleGradient* to, SvgStyleGradient* from)
2468 {
2469 to->radial->fx = from->radial->fx;
2470 to->radial->isFxPercentage = from->radial->isFxPercentage;
2471 to->flags = (to->flags | SvgGradientFlags::Fx);
2472 }
2473
2474
2475 static void _inheritRadialFyAttr(SvgStyleGradient* to, SvgStyleGradient* from)
2476 {
2477 to->radial->fy = from->radial->fy;
2478 to->radial->isFyPercentage = from->radial->isFyPercentage;
2479 to->flags = (to->flags | SvgGradientFlags::Fy);
2480 }
2481
2482
2483 static void _inheritRadialFrAttr(SvgStyleGradient* to, SvgStyleGradient* from)
2484 {
2485 to->radial->fr = from->radial->fr;
2486 to->radial->isFrPercentage = from->radial->isFrPercentage;
2487 to->flags = (to->flags | SvgGradientFlags::Fr);
2488 }
2489
2490
2491 static void _inheritRadialRAttr(SvgStyleGradient* to, SvgStyleGradient* from)
2492 {
2493 to->radial->r = from->radial->r;
2494 to->radial->isRPercentage = from->radial->isRPercentage;
2495 to->flags = (to->flags | SvgGradientFlags::R);
2496 }
2497
2498
2499 typedef void (*radialMethod)(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value);
2500 typedef void (*radialInheritMethod)(SvgStyleGradient* to, SvgStyleGradient* from);
2501 typedef void (*radialMethodRecalc)(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace);
2502
2503
2504 #define RADIAL_DEF(Name, Name1, Flag) \
2505 { \
2506 #Name, sizeof(#Name), _handleRadial##Name1##Attr, _inheritRadial##Name1##Attr, _recalcRadial##Name1##Attr, _recalcInheritedRadial##Name1##Attr, Flag \
2507 }
2508
2509
2510 static constexpr struct
2511 {
2512 const char* tag;
2513 int sz;
2514 radialMethod tagHandler;
2515 radialInheritMethod tagInheritHandler;
2516 radialMethodRecalc tagRecalc;
2517 radialMethodRecalc tagInheritedRecalc;
2518 SvgGradientFlags flag;
2519 } radialTags[] = {
2520 RADIAL_DEF(cx, Cx, SvgGradientFlags::Cx),
2521 RADIAL_DEF(cy, Cy, SvgGradientFlags::Cy),
2522 RADIAL_DEF(fx, Fx, SvgGradientFlags::Fx),
2523 RADIAL_DEF(fy, Fy, SvgGradientFlags::Fy),
2524 RADIAL_DEF(r, R, SvgGradientFlags::R),
2525 RADIAL_DEF(fr, Fr, SvgGradientFlags::Fr)
2526 };
2527
2528
2529 static bool _attrParseRadialGradientNode(void* data, const char* key, const char* value)
2530 {
2531 SvgLoaderData* loader = (SvgLoaderData*)data;
2532 SvgStyleGradient* grad = loader->svgParse->styleGrad;
2533 SvgRadialGradient* radial = grad->radial;
2534 int sz = strlen(key);
2535
2536 for (unsigned int i = 0; i < sizeof(radialTags) / sizeof(radialTags[0]); i++) {
2537 if (radialTags[i].sz - 1 == sz && !strncmp(radialTags[i].tag, key, sz)) {
2538 radialTags[i].tagHandler(loader, radial, value);
2539 grad->flags = (grad->flags | radialTags[i].flag);
2540 return true;
2541 }
2542 }
2543
2544 if (!strcmp(key, "id")) {
2545 if (grad->id && value) free(grad->id);
2546 grad->id = _copyId(value);
2547 } else if (!strcmp(key, "spreadMethod")) {
2548 grad->spread = _parseSpreadValue(value);
2549 grad->flags = (grad->flags | SvgGradientFlags::SpreadMethod);
2550 } else if (!strcmp(key, "href") || !strcmp(key, "xlink:href")) {
2551 if (grad->ref && value) free(grad->ref);
2552 grad->ref = _idFromHref(value);
2553 } else if (!strcmp(key, "gradientUnits")) {
2554 if (!strcmp(value, "userSpaceOnUse")) grad->userSpace = true;
2555 grad->flags = (grad->flags | SvgGradientFlags::GradientUnits);
2556 } else if (!strcmp(key, "gradientTransform")) {
2557 grad->transform = _parseTransformationMatrix(value);
2558 } else {
2559 return false;
2560 }
2561
2562 return true;
2563 }
2564
2565
2566 static SvgStyleGradient* _createRadialGradient(SvgLoaderData* loader, const char* buf, unsigned bufLength)
2567 {
2568 auto grad = (SvgStyleGradient*)(calloc(1, sizeof(SvgStyleGradient)));
2569 loader->svgParse->styleGrad = grad;
2570
2571 grad->flags = SvgGradientFlags::None;
2572 grad->type = SvgGradientType::Radial;
2573 grad->userSpace = false;
2574 grad->radial = (SvgRadialGradient*)calloc(1, sizeof(SvgRadialGradient));
2575 if (!grad->radial) {
2576 grad->clear();
2577 free(grad);
2578 return nullptr;
2579 }
2580 /**
2581 * Default values of gradient transformed into global percentage
2582 */
2583 grad->radial->cx = 0.5f;
2584 grad->radial->cy = 0.5f;
2585 grad->radial->fx = 0.5f;
2586 grad->radial->fy = 0.5f;
2587 grad->radial->r = 0.5f;
2588 grad->radial->isCxPercentage = true;
2589 grad->radial->isCyPercentage = true;
2590 grad->radial->isFxPercentage = true;
2591 grad->radial->isFyPercentage = true;
2592 grad->radial->isRPercentage = true;
2593 grad->radial->isFrPercentage = true;
2594
2595 loader->svgParse->gradient.parsedFx = false;
2596 loader->svgParse->gradient.parsedFy = false;
2597 simpleXmlParseAttributes(buf, bufLength,
2598 _attrParseRadialGradientNode, loader);
2599
2600 for (unsigned int i = 0; i < sizeof(radialTags) / sizeof(radialTags[0]); i++) {
2601 radialTags[i].tagRecalc(loader, grad->radial, grad->userSpace);
2602 }
2603
2604 return loader->svgParse->styleGrad;
2605 }
2606
2607
2608 static SvgColor* _findLatestColor(const SvgLoaderData* loader)
2609 {
2610 auto parent = loader->stack.count > 0 ? loader->stack.last() : loader->doc;
2611
2612 while (parent != nullptr) {
2613 if (parent->style->curColorSet) return &parent->style->color;
2614 parent = parent->parent;
2615 }
2616 return nullptr;
2617 }
2618
2619
2620 static bool _attrParseStopsStyle(void* data, const char* key, const char* value)
2621 {
2622 SvgLoaderData* loader = (SvgLoaderData*)data;
2623 auto stop = &loader->svgParse->gradStop;
2624
2625 if (!strcmp(key, "stop-opacity")) {
2626 stop->a = _toOpacity(value);
2627 loader->svgParse->flags = (loader->svgParse->flags | SvgStopStyleFlags::StopOpacity);
2628 } else if (!strcmp(key, "stop-color")) {
2629 if (!strcmp(value, "currentColor")) {
2630 if (auto latestColor = _findLatestColor(loader)) {
2631 stop->r = latestColor->r;
2632 stop->g = latestColor->g;
2633 stop->b = latestColor->b;
2634 }
2635 } else if (_toColor(value, &stop->r, &stop->g, &stop->b, nullptr)) {
2636 loader->svgParse->flags = (loader->svgParse->flags | SvgStopStyleFlags::StopColor);
2637 }
2638 } else {
2639 return false;
2640 }
2641
2642 return true;
2643 }
2644
2645
2646 static bool _attrParseStops(void* data, const char* key, const char* value)
2647 {
2648 SvgLoaderData* loader = (SvgLoaderData*)data;
2649 auto stop = &loader->svgParse->gradStop;
2650
2651 if (!strcmp(key, "offset")) {
2652 stop->offset = _toOffset(value);
2653 } else if (!strcmp(key, "stop-opacity")) {
2654 if (!(loader->svgParse->flags & SvgStopStyleFlags::StopOpacity)) {
2655 stop->a = _toOpacity(value);
2656 }
2657 } else if (!strcmp(key, "stop-color")) {
2658 if (!strcmp(value, "currentColor")) {
2659 if (auto latestColor = _findLatestColor(loader)) {
2660 stop->r = latestColor->r;
2661 stop->g = latestColor->g;
2662 stop->b = latestColor->b;
2663 }
2664 } else if (!(loader->svgParse->flags & SvgStopStyleFlags::StopColor)) {
2665 _toColor(value, &stop->r, &stop->g, &stop->b, nullptr);
2666 }
2667 } else if (!strcmp(key, "style")) {
2668 simpleXmlParseW3CAttribute(value, strlen(value), _attrParseStopsStyle, data);
2669 } else {
2670 return false;
2671 }
2672
2673 return true;
2674 }
2675
2676
2677 static void _handleLinearX1Attr(SvgLoaderData* loader, SvgLinearGradient* linear, const char* value)
2678 {
2679 linear->x1 = _gradientToFloat(loader->svgParse, value, linear->isX1Percentage);
2680 }
2681
2682
2683 static void _handleLinearY1Attr(SvgLoaderData* loader, SvgLinearGradient* linear, const char* value)
2684 {
2685 linear->y1 = _gradientToFloat(loader->svgParse, value, linear->isY1Percentage);
2686 }
2687
2688
2689 static void _handleLinearX2Attr(SvgLoaderData* loader, SvgLinearGradient* linear, const char* value)
2690 {
2691 linear->x2 = _gradientToFloat(loader->svgParse, value, linear->isX2Percentage);
2692 }
2693
2694
2695 static void _handleLinearY2Attr(SvgLoaderData* loader, SvgLinearGradient* linear, const char* value)
2696 {
2697 linear->y2 = _gradientToFloat(loader->svgParse, value, linear->isY2Percentage);
2698 }
2699
2700
2701 static void _recalcLinearX1Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
2702 {
2703 if (userSpace && !linear->isX1Percentage) linear->x1 = linear->x1 / loader->svgParse->global.w;
2704 }
2705
2706
2707 static void _recalcLinearY1Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
2708 {
2709 if (userSpace && !linear->isY1Percentage) linear->y1 = linear->y1 / loader->svgParse->global.h;
2710 }
2711
2712
2713 static void _recalcLinearX2Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
2714 {
2715 if (userSpace && !linear->isX2Percentage) linear->x2 = linear->x2 / loader->svgParse->global.w;
2716 }
2717
2718
2719 static void _recalcLinearY2Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
2720 {
2721 if (userSpace && !linear->isY2Percentage) linear->y2 = linear->y2 / loader->svgParse->global.h;
2722 }
2723
2724
2725 static void _recalcInheritedLinearX1Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
2726 {
2727 if (!linear->isX1Percentage) {
2728 if (userSpace) linear->x1 /= loader->svgParse->global.w;
2729 else linear->x1 *= loader->svgParse->global.w;
2730 }
2731 }
2732
2733
2734 static void _recalcInheritedLinearX2Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
2735 {
2736 if (!linear->isX2Percentage) {
2737 if (userSpace) linear->x2 /= loader->svgParse->global.w;
2738 else linear->x2 *= loader->svgParse->global.w;
2739 }
2740 }
2741
2742
2743 static void _recalcInheritedLinearY1Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
2744 {
2745 if (!linear->isY1Percentage) {
2746 if (userSpace) linear->y1 /= loader->svgParse->global.h;
2747 else linear->y1 *= loader->svgParse->global.h;
2748 }
2749 }
2750
2751
2752 static void _recalcInheritedLinearY2Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
2753 {
2754 if (!linear->isY2Percentage) {
2755 if (userSpace) linear->y2 /= loader->svgParse->global.h;
2756 else linear->y2 *= loader->svgParse->global.h;
2757 }
2758 }
2759
2760
2761 static void _inheritLinearX1Attr(SvgStyleGradient* to, SvgStyleGradient* from)
2762 {
2763 to->linear->x1 = from->linear->x1;
2764 to->linear->isX1Percentage = from->linear->isX1Percentage;
2765 to->flags = (to->flags | SvgGradientFlags::X1);
2766 }
2767
2768
2769 static void _inheritLinearX2Attr(SvgStyleGradient* to, SvgStyleGradient* from)
2770 {
2771 to->linear->x2 = from->linear->x2;
2772 to->linear->isX2Percentage = from->linear->isX2Percentage;
2773 to->flags = (to->flags | SvgGradientFlags::X2);
2774 }
2775
2776
2777 static void _inheritLinearY1Attr(SvgStyleGradient* to, SvgStyleGradient* from)
2778 {
2779 to->linear->y1 = from->linear->y1;
2780 to->linear->isY1Percentage = from->linear->isY1Percentage;
2781 to->flags = (to->flags | SvgGradientFlags::Y1);
2782 }
2783
2784
2785 static void _inheritLinearY2Attr(SvgStyleGradient* to, SvgStyleGradient* from)
2786 {
2787 to->linear->y2 = from->linear->y2;
2788 to->linear->isY2Percentage = from->linear->isY2Percentage;
2789 to->flags = (to->flags | SvgGradientFlags::Y2);
2790 }
2791
2792
2793 typedef void (*Linear_Method)(SvgLoaderData* loader, SvgLinearGradient* linear, const char* value);
2794 typedef void (*Linear_Inherit_Method)(SvgStyleGradient* to, SvgStyleGradient* from);
2795 typedef void (*Linear_Method_Recalc)(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace);
2796
2797
2798 #define LINEAR_DEF(Name, Name1, Flag) \
2799 { \
2800 #Name, sizeof(#Name), _handleLinear##Name1##Attr, _inheritLinear##Name1##Attr, _recalcLinear##Name1##Attr, _recalcInheritedLinear##Name1##Attr, Flag \
2801 }
2802
2803
2804 static constexpr struct
2805 {
2806 const char* tag;
2807 int sz;
2808 Linear_Method tagHandler;
2809 Linear_Inherit_Method tagInheritHandler;
2810 Linear_Method_Recalc tagRecalc;
2811 Linear_Method_Recalc tagInheritedRecalc;
2812 SvgGradientFlags flag;
2813 } linear_tags[] = {
2814 LINEAR_DEF(x1, X1, SvgGradientFlags::X1),
2815 LINEAR_DEF(y1, Y1, SvgGradientFlags::Y1),
2816 LINEAR_DEF(x2, X2, SvgGradientFlags::X2),
2817 LINEAR_DEF(y2, Y2, SvgGradientFlags::Y2)
2818 };
2819
2820
2821 static bool _attrParseLinearGradientNode(void* data, const char* key, const char* value)
2822 {
2823 SvgLoaderData* loader = (SvgLoaderData*)data;
2824 SvgStyleGradient* grad = loader->svgParse->styleGrad;
2825 SvgLinearGradient* linear = grad->linear;
2826 int sz = strlen(key);
2827
2828 for (unsigned int i = 0; i < sizeof(linear_tags) / sizeof(linear_tags[0]); i++) {
2829 if (linear_tags[i].sz - 1 == sz && !strncmp(linear_tags[i].tag, key, sz)) {
2830 linear_tags[i].tagHandler(loader, linear, value);
2831 grad->flags = (grad->flags | linear_tags[i].flag);
2832 return true;
2833 }
2834 }
2835
2836 if (!strcmp(key, "id")) {
2837 if (grad->id && value) free(grad->id);
2838 grad->id = _copyId(value);
2839 } else if (!strcmp(key, "spreadMethod")) {
2840 grad->spread = _parseSpreadValue(value);
2841 grad->flags = (grad->flags | SvgGradientFlags::SpreadMethod);
2842 } else if (!strcmp(key, "href") || !strcmp(key, "xlink:href")) {
2843 if (grad->ref && value) free(grad->ref);
2844 grad->ref = _idFromHref(value);
2845 } else if (!strcmp(key, "gradientUnits")) {
2846 if (!strcmp(value, "userSpaceOnUse")) grad->userSpace = true;
2847 grad->flags = (grad->flags | SvgGradientFlags::GradientUnits);
2848 } else if (!strcmp(key, "gradientTransform")) {
2849 grad->transform = _parseTransformationMatrix(value);
2850 } else {
2851 return false;
2852 }
2853
2854 return true;
2855 }
2856
2857
2858 static SvgStyleGradient* _createLinearGradient(SvgLoaderData* loader, const char* buf, unsigned bufLength)
2859 {
2860 auto grad = (SvgStyleGradient*)(calloc(1, sizeof(SvgStyleGradient)));
2861 loader->svgParse->styleGrad = grad;
2862
2863 grad->flags = SvgGradientFlags::None;
2864 grad->type = SvgGradientType::Linear;
2865 grad->userSpace = false;
2866 grad->linear = (SvgLinearGradient*)calloc(1, sizeof(SvgLinearGradient));
2867 if (!grad->linear) {
2868 grad->clear();
2869 free(grad);
2870 return nullptr;
2871 }
2872 /**
2873 * Default value of x2 is 100% - transformed to the global percentage
2874 */
2875 grad->linear->x2 = 1.0f;
2876 grad->linear->isX2Percentage = true;
2877
2878 simpleXmlParseAttributes(buf, bufLength, _attrParseLinearGradientNode, loader);
2879
2880 for (unsigned int i = 0; i < sizeof(linear_tags) / sizeof(linear_tags[0]); i++) {
2881 linear_tags[i].tagRecalc(loader, grad->linear, grad->userSpace);
2882 }
2883
2884 return loader->svgParse->styleGrad;
2885 }
2886
2887
2888 #define GRADIENT_DEF(Name, Name1) \
2889 { \
2890 #Name, sizeof(#Name), _create##Name1 \
2891 }
2892
2893
2894 /**
2895 * In the case when the gradients lengths are given as numbers (not percentages)
2896 * in the current user coordinate system, they are recalculated into percentages
2897 * related to the canvas width and height.
2898 */
2899 static constexpr struct
2900 {
2901 const char* tag;
2902 int sz;
2903 GradientFactoryMethod tagHandler;
2904 } gradientTags[] = {
2905 GRADIENT_DEF(linearGradient, LinearGradient),
2906 GRADIENT_DEF(radialGradient, RadialGradient)
2907 };
2908
2909
2910 static GradientFactoryMethod _findGradientFactory(const char* name)
2911 {
2912 int sz = strlen(name);
2913
2914 for (unsigned int i = 0; i < sizeof(gradientTags) / sizeof(gradientTags[0]); i++) {
2915 if (gradientTags[i].sz - 1 == sz && !strncmp(gradientTags[i].tag, name, sz)) {
2916 return gradientTags[i].tagHandler;
2917 }
2918 }
2919 return nullptr;
2920 }
2921
2922
2923 static void _cloneGradStops(Array<Fill::ColorStop>& dst, const Array<Fill::ColorStop>& src)
2924 {
2925 for (uint32_t i = 0; i < src.count; ++i) {
2926 dst.push(src[i]);
2927 }
2928 }
2929
2930
2931 static void _inheritGradient(SvgLoaderData* loader, SvgStyleGradient* to, SvgStyleGradient* from)
2932 {
2933 if (!to || !from) return;
2934
2935 if (!(to->flags & SvgGradientFlags::SpreadMethod) && (from->flags & SvgGradientFlags::SpreadMethod)) {
2936 to->spread = from->spread;
2937 to->flags = (to->flags | SvgGradientFlags::SpreadMethod);
2938 }
2939 bool gradUnitSet = (to->flags & SvgGradientFlags::GradientUnits);
2940 if (!(to->flags & SvgGradientFlags::GradientUnits) && (from->flags & SvgGradientFlags::GradientUnits)) {
2941 to->userSpace = from->userSpace;
2942 to->flags = (to->flags | SvgGradientFlags::GradientUnits);
2943 }
2944
2945 if (!to->transform && from->transform) {
2946 to->transform = (Matrix*)malloc(sizeof(Matrix));
2947 if (to->transform) memcpy(to->transform, from->transform, sizeof(Matrix));
2948 }
2949
2950 if (to->type == SvgGradientType::Linear) {
2951 for (unsigned int i = 0; i < sizeof(linear_tags) / sizeof(linear_tags[0]); i++) {
2952 bool coordSet = to->flags & linear_tags[i].flag;
2953 if (!(to->flags & linear_tags[i].flag) && (from->flags & linear_tags[i].flag)) {
2954 linear_tags[i].tagInheritHandler(to, from);
2955 }
2956
2957 //GradUnits not set directly, coord set
2958 if (!gradUnitSet && coordSet) {
2959 linear_tags[i].tagRecalc(loader, to->linear, to->userSpace);
2960 }
2961 //GradUnits set, coord not set directly
2962 if (to->userSpace == from->userSpace) continue;
2963 if (gradUnitSet && !coordSet) {
2964 linear_tags[i].tagInheritedRecalc(loader, to->linear, to->userSpace);
2965 }
2966 }
2967 } else if (to->type == SvgGradientType::Radial) {
2968 for (unsigned int i = 0; i < sizeof(radialTags) / sizeof(radialTags[0]); i++) {
2969 bool coordSet = (to->flags & radialTags[i].flag);
2970 if (!(to->flags & radialTags[i].flag) && (from->flags & radialTags[i].flag)) {
2971 radialTags[i].tagInheritHandler(to, from);
2972 }
2973
2974 //GradUnits not set directly, coord set
2975 if (!gradUnitSet && coordSet) {
2976 radialTags[i].tagRecalc(loader, to->radial, to->userSpace);
2977 //If fx and fy are not set, set cx and cy.
2978 if (!strcmp(radialTags[i].tag, "cx") && !(to->flags & SvgGradientFlags::Fx)) to->radial->fx = to->radial->cx;
2979 if (!strcmp(radialTags[i].tag, "cy") && !(to->flags & SvgGradientFlags::Fy)) to->radial->fy = to->radial->cy;
2980 }
2981 //GradUnits set, coord not set directly
2982 if (to->userSpace == from->userSpace) continue;
2983 if (gradUnitSet && !coordSet) {
2984 //If fx and fx are not set, do not call recalc.
2985 if (!strcmp(radialTags[i].tag, "fx") && !(to->flags & SvgGradientFlags::Fx)) continue;
2986 if (!strcmp(radialTags[i].tag, "fy") && !(to->flags & SvgGradientFlags::Fy)) continue;
2987 radialTags[i].tagInheritedRecalc(loader, to->radial, to->userSpace);
2988 }
2989 }
2990 }
2991
2992 if (to->stops.empty()) _cloneGradStops(to->stops, from->stops);
2993 }
2994
2995
2996 static SvgStyleGradient* _cloneGradient(SvgStyleGradient* from)
2997 {
2998 if (!from) return nullptr;
2999
3000 auto grad = (SvgStyleGradient*)(calloc(1, sizeof(SvgStyleGradient)));
3001 if (!grad) return nullptr;
3002
3003 grad->type = from->type;
3004 grad->id = from->id ? _copyId(from->id) : nullptr;
3005 grad->ref = from->ref ? _copyId(from->ref) : nullptr;
3006 grad->spread = from->spread;
3007 grad->userSpace = from->userSpace;
3008 grad->flags = from->flags;
3009
3010 if (from->transform) {
3011 grad->transform = (Matrix*)calloc(1, sizeof(Matrix));
3012 if (grad->transform) memcpy(grad->transform, from->transform, sizeof(Matrix));
3013 }
3014
3015 if (grad->type == SvgGradientType::Linear) {
3016 grad->linear = (SvgLinearGradient*)calloc(1, sizeof(SvgLinearGradient));
3017 if (!grad->linear) goto error_grad_alloc;
3018 memcpy(grad->linear, from->linear, sizeof(SvgLinearGradient));
3019 } else if (grad->type == SvgGradientType::Radial) {
3020 grad->radial = (SvgRadialGradient*)calloc(1, sizeof(SvgRadialGradient));
3021 if (!grad->radial) goto error_grad_alloc;
3022 memcpy(grad->radial, from->radial, sizeof(SvgRadialGradient));
3023 }
3024
3025 _cloneGradStops(grad->stops, from->stops);
3026
3027 return grad;
3028
3029 error_grad_alloc:
3030 if (grad) {
3031 grad->clear();
3032 free(grad);
3033 }
3034 return nullptr;
3035 }
3036
3037
3038 static void _styleInherit(SvgStyleProperty* child, const SvgStyleProperty* parent)
3039 {
3040 if (parent == nullptr) return;
3041 //Inherit the property of parent if not present in child.
3042 if (!child->curColorSet) {
3043 child->color = parent->color;
3044 child->curColorSet = parent->curColorSet;
3045 }
3046 if (!(child->flags & SvgStyleFlags::PaintOrder)) {
3047 child->paintOrder = parent->paintOrder;
3048 }
3049 //Fill
3050 if (!(child->fill.flags & SvgFillFlags::Paint)) {
3051 child->fill.paint.color = parent->fill.paint.color;
3052 child->fill.paint.none = parent->fill.paint.none;
3053 child->fill.paint.curColor = parent->fill.paint.curColor;
3054 if (parent->fill.paint.url) {
3055 if (child->fill.paint.url) free(child->fill.paint.url);
3056 child->fill.paint.url = _copyId(parent->fill.paint.url);
3057 }
3058 }
3059 if (!(child->fill.flags & SvgFillFlags::Opacity)) {
3060 child->fill.opacity = parent->fill.opacity;
3061 }
3062 if (!(child->fill.flags & SvgFillFlags::FillRule)) {
3063 child->fill.fillRule = parent->fill.fillRule;
3064 }
3065 //Stroke
3066 if (!(child->stroke.flags & SvgStrokeFlags::Paint)) {
3067 child->stroke.paint.color = parent->stroke.paint.color;
3068 child->stroke.paint.none = parent->stroke.paint.none;
3069 child->stroke.paint.curColor = parent->stroke.paint.curColor;
3070 if (parent->stroke.paint.url) {
3071 if (child->stroke.paint.url) free(child->stroke.paint.url);
3072 child->stroke.paint.url = _copyId(parent->stroke.paint.url);
3073 }
3074 }
3075 if (!(child->stroke.flags & SvgStrokeFlags::Opacity)) {
3076 child->stroke.opacity = parent->stroke.opacity;
3077 }
3078 if (!(child->stroke.flags & SvgStrokeFlags::Width)) {
3079 child->stroke.width = parent->stroke.width;
3080 }
3081 if (!(child->stroke.flags & SvgStrokeFlags::Dash)) {
3082 if (parent->stroke.dash.array.count > 0) {
3083 child->stroke.dash.array.clear();
3084 child->stroke.dash.array.reserve(parent->stroke.dash.array.count);
3085 for (uint32_t i = 0; i < parent->stroke.dash.array.count; ++i) {
3086 child->stroke.dash.array.push(parent->stroke.dash.array[i]);
3087 }
3088 }
3089 }
3090 if (!(child->stroke.flags & SvgStrokeFlags::DashOffset)) {
3091 child->stroke.dash.offset = parent->stroke.dash.offset;
3092 }
3093 if (!(child->stroke.flags & SvgStrokeFlags::Cap)) {
3094 child->stroke.cap = parent->stroke.cap;
3095 }
3096 if (!(child->stroke.flags & SvgStrokeFlags::Join)) {
3097 child->stroke.join = parent->stroke.join;
3098 }
3099 if (!(child->stroke.flags & SvgStrokeFlags::Miterlimit)) {
3100 child->stroke.miterlimit = parent->stroke.miterlimit;
3101 }
3102 }
3103
3104
3105 static void _styleCopy(SvgStyleProperty* to, const SvgStyleProperty* from)
3106 {
3107 if (from == nullptr) return;
3108 //Copy the properties of 'from' only if they were explicitly set (not the default ones).
3109 if (from->curColorSet) {
3110 to->color = from->color;
3111 to->curColorSet = true;
3112 }
3113 if (from->flags & SvgStyleFlags::Opacity) {
3114 to->opacity = from->opacity;
3115 }
3116 if (from->flags & SvgStyleFlags::PaintOrder) {
3117 to->paintOrder = from->paintOrder;
3118 }
3119 if (from->flags & SvgStyleFlags::Display) {
3120 to->display = from->display;
3121 }
3122 //Fill
3123 to->fill.flags = (to->fill.flags | from->fill.flags);
3124 if (from->fill.flags & SvgFillFlags::Paint) {
3125 to->fill.paint.color = from->fill.paint.color;
3126 to->fill.paint.none = from->fill.paint.none;
3127 to->fill.paint.curColor = from->fill.paint.curColor;
3128 if (from->fill.paint.url) {
3129 if (to->fill.paint.url) free(to->fill.paint.url);
3130 to->fill.paint.url = _copyId(from->fill.paint.url);
3131 }
3132 }
3133 if (from->fill.flags & SvgFillFlags::Opacity) {
3134 to->fill.opacity = from->fill.opacity;
3135 }
3136 if (from->fill.flags & SvgFillFlags::FillRule) {
3137 to->fill.fillRule = from->fill.fillRule;
3138 }
3139 //Stroke
3140 to->stroke.flags = (to->stroke.flags | from->stroke.flags);
3141 if (from->stroke.flags & SvgStrokeFlags::Paint) {
3142 to->stroke.paint.color = from->stroke.paint.color;
3143 to->stroke.paint.none = from->stroke.paint.none;
3144 to->stroke.paint.curColor = from->stroke.paint.curColor;
3145 if (from->stroke.paint.url) {
3146 if (to->stroke.paint.url) free(to->stroke.paint.url);
3147 to->stroke.paint.url = _copyId(from->stroke.paint.url);
3148 }
3149 }
3150 if (from->stroke.flags & SvgStrokeFlags::Opacity) {
3151 to->stroke.opacity = from->stroke.opacity;
3152 }
3153 if (from->stroke.flags & SvgStrokeFlags::Width) {
3154 to->stroke.width = from->stroke.width;
3155 }
3156 if (from->stroke.flags & SvgStrokeFlags::Dash) {
3157 if (from->stroke.dash.array.count > 0) {
3158 to->stroke.dash.array.clear();
3159 to->stroke.dash.array.reserve(from->stroke.dash.array.count);
3160 for (uint32_t i = 0; i < from->stroke.dash.array.count; ++i) {
3161 to->stroke.dash.array.push(from->stroke.dash.array[i]);
3162 }
3163 }
3164 }
3165 if (from->stroke.flags & SvgStrokeFlags::DashOffset) {
3166 to->stroke.dash.offset = from->stroke.dash.offset;
3167 }
3168 if (from->stroke.flags & SvgStrokeFlags::Cap) {
3169 to->stroke.cap = from->stroke.cap;
3170 }
3171 if (from->stroke.flags & SvgStrokeFlags::Join) {
3172 to->stroke.join = from->stroke.join;
3173 }
3174 if (from->stroke.flags & SvgStrokeFlags::Miterlimit) {
3175 to->stroke.miterlimit = from->stroke.miterlimit;
3176 }
3177 }
3178
3179
3180 static void _copyAttr(SvgNode* to, const SvgNode* from)
3181 {
3182 //Copy matrix attribute
3183 if (from->transform) {
3184 to->transform = (Matrix*)malloc(sizeof(Matrix));
3185 if (to->transform) *to->transform = *from->transform;
3186 }
3187 //Copy style attribute
3188 _styleCopy(to->style, from->style);
3189 to->style->flags = (to->style->flags | from->style->flags);
3190 if (from->style->clipPath.url) {
3191 if (to->style->clipPath.url) free(to->style->clipPath.url);
3192 to->style->clipPath.url = strdup(from->style->clipPath.url);
3193 }
3194 if (from->style->mask.url) {
3195 if (to->style->mask.url) free(to->style->mask.url);
3196 to->style->mask.url = strdup(from->style->mask.url);
3197 }
3198
3199 //Copy node attribute
3200 switch (from->type) {
3201 case SvgNodeType::Circle: {
3202 to->node.circle.cx = from->node.circle.cx;
3203 to->node.circle.cy = from->node.circle.cy;
3204 to->node.circle.r = from->node.circle.r;
3205 break;
3206 }
3207 case SvgNodeType::Ellipse: {
3208 to->node.ellipse.cx = from->node.ellipse.cx;
3209 to->node.ellipse.cy = from->node.ellipse.cy;
3210 to->node.ellipse.rx = from->node.ellipse.rx;
3211 to->node.ellipse.ry = from->node.ellipse.ry;
3212 break;
3213 }
3214 case SvgNodeType::Rect: {
3215 to->node.rect.x = from->node.rect.x;
3216 to->node.rect.y = from->node.rect.y;
3217 to->node.rect.w = from->node.rect.w;
3218 to->node.rect.h = from->node.rect.h;
3219 to->node.rect.rx = from->node.rect.rx;
3220 to->node.rect.ry = from->node.rect.ry;
3221 to->node.rect.hasRx = from->node.rect.hasRx;
3222 to->node.rect.hasRy = from->node.rect.hasRy;
3223 break;
3224 }
3225 case SvgNodeType::Line: {
3226 to->node.line.x1 = from->node.line.x1;
3227 to->node.line.y1 = from->node.line.y1;
3228 to->node.line.x2 = from->node.line.x2;
3229 to->node.line.y2 = from->node.line.y2;
3230 break;
3231 }
3232 case SvgNodeType::Path: {
3233 if (from->node.path.path) {
3234 if (to->node.path.path) free(to->node.path.path);
3235 to->node.path.path = strdup(from->node.path.path);
3236 }
3237 break;
3238 }
3239 case SvgNodeType::Polygon: {
3240 if ((to->node.polygon.pts.count = from->node.polygon.pts.count)) {
3241 to->node.polygon.pts = from->node.polygon.pts;
3242 }
3243 break;
3244 }
3245 case SvgNodeType::Polyline: {
3246 if ((to->node.polyline.pts.count = from->node.polyline.pts.count)) {
3247 to->node.polyline.pts = from->node.polyline.pts;
3248 }
3249 break;
3250 }
3251 case SvgNodeType::Image: {
3252 to->node.image.x = from->node.image.x;
3253 to->node.image.y = from->node.image.y;
3254 to->node.image.w = from->node.image.w;
3255 to->node.image.h = from->node.image.h;
3256 if (from->node.image.href) {
3257 if (to->node.image.href) free(to->node.image.href);
3258 to->node.image.href = strdup(from->node.image.href);
3259 }
3260 break;
3261 }
3262 case SvgNodeType::Use: {
3263 to->node.use.x = from->node.use.x;
3264 to->node.use.y = from->node.use.y;
3265 to->node.use.w = from->node.use.w;
3266 to->node.use.h = from->node.use.h;
3267 to->node.use.isWidthSet = from->node.use.isWidthSet;
3268 to->node.use.isHeightSet = from->node.use.isHeightSet;
3269 to->node.use.symbol = from->node.use.symbol;
3270 break;
3271 }
3272 case SvgNodeType::Text: {
3273 to->node.text.x = from->node.text.x;
3274 to->node.text.y = from->node.text.y;
3275 to->node.text.fontSize = from->node.text.fontSize;
3276 if (from->node.text.text) {
3277 if (to->node.text.text) free(to->node.text.text);
3278 to->node.text.text = strdup(from->node.text.text);
3279 }
3280 if (from->node.text.fontFamily) {
3281 if (to->node.text.fontFamily) free(to->node.text.fontFamily);
3282 to->node.text.fontFamily = strdup(from->node.text.fontFamily);
3283 }
3284 break;
3285 }
3286 default: {
3287 break;
3288 }
3289 }
3290 }
3291
3292
3293 static void _cloneNode(SvgNode* from, SvgNode* parent, int depth)
3294 {
3295 /* Exception handling: Prevent invalid SVG data input.
3296 The size is the arbitrary value, we need an experimental size. */
3297 if (depth == 8192) {
3298 TVGERR("SVG", "Infinite recursive call - stopped after %d calls! Svg file may be incorrectly formatted.", depth);
3299 return;
3300 }
3301
3302 SvgNode* newNode;
3303 if (!from || !parent || from == parent) return;
3304
3305 newNode = _createNode(parent, from->type);
3306 if (!newNode) return;
3307
3308 _styleInherit(newNode->style, parent->style);
3309 _copyAttr(newNode, from);
3310
3311 auto child = from->child.data;
3312 for (uint32_t i = 0; i < from->child.count; ++i, ++child) {
3313 _cloneNode(*child, newNode, depth + 1);
3314 }
3315 }
3316
3317
3318 static void _clonePostponedNodes(Inlist<SvgNodeIdPair>* cloneNodes, SvgNode* doc)
3319 {
3320 auto nodeIdPair = cloneNodes->front();
3321 while (nodeIdPair) {
3322 if (!_findParentById(nodeIdPair->node, nodeIdPair->id, doc)) {
3323 //Check if none of nodeFrom's children are in the cloneNodes list
3324 auto postpone = false;
3325 auto nodeFrom = _findNodeById(_getDefsNode(nodeIdPair->node), nodeIdPair->id);
3326 if (!nodeFrom) nodeFrom = _findNodeById(doc, nodeIdPair->id);
3327 if (nodeFrom) {
3328 for (auto pair = cloneNodes->head; pair; pair = pair->next) {
3329 if (_checkPostponed(nodeFrom, pair->node, 1)) {
3330 postpone = true;
3331 cloneNodes->back(nodeIdPair);
3332 break;
3333 }
3334 }
3335 }
3336 //Since none of the child nodes of nodeFrom are present in the cloneNodes list, it can be cloned immediately
3337 if (!postpone) {
3338 _cloneNode(nodeFrom, nodeIdPair->node, 0);
3339 if (nodeFrom && nodeFrom->type == SvgNodeType::Symbol && nodeIdPair->node->type == SvgNodeType::Use) {
3340 nodeIdPair->node->node.use.symbol = nodeFrom;
3341 }
3342 free(nodeIdPair->id);
3343 free(nodeIdPair);
3344 }
3345 } else {
3346 TVGLOG("SVG", "%s is ancestor element. This reference is invalid.", nodeIdPair->id);
3347 free(nodeIdPair->id);
3348 free(nodeIdPair);
3349 }
3350 nodeIdPair = cloneNodes->front();
3351 }
3352 }
3353
3354
3355 static void _svgLoaderParserXmlClose(SvgLoaderData* loader, const char* content, unsigned int length)
3356 {
3357 const char* itr = nullptr;
3358 int sz = length;
3359 char tagName[20] = "";
3360
3361 content = _skipSpace(content, nullptr);
3362 itr = content;
3363 while ((itr != nullptr) && *itr != '>') itr++;
3364
3365 if (itr) {
3366 sz = itr - content;
3367 while ((sz > 0) && (isspace(content[sz - 1]))) sz--;
3368 if ((unsigned int)sz >= sizeof(tagName)) sz = sizeof(tagName) - 1;
3369 strncpy(tagName, content, sz);
3370 tagName[sz] = '\0';
3371 }
3372 else return;
3373
3374 for (unsigned int i = 0; i < sizeof(groupTags) / sizeof(groupTags[0]); i++) {
3375 if (!strncmp(tagName, groupTags[i].tag, sz)) {
3376 loader->stack.pop();
3377 break;
3378 }
3379 }
3380
3381 for (unsigned int i = 0; i < sizeof(gradientTags) / sizeof(gradientTags[0]); i++) {
3382 if (!strncmp(tagName, gradientTags[i].tag, sz)) {
3383 loader->gradientStack.pop();
3384 break;
3385 }
3386 }
3387
3388 for (unsigned int i = 0; i < sizeof(graphicsTags) / sizeof(graphicsTags[0]); i++) {
3389 if (!strncmp(tagName, graphicsTags[i].tag, sz)) {
3390 loader->currentGraphicsNode = nullptr;
3391 if (!strncmp(tagName, "text", 4)) loader->openedTag = OpenedTagType::Other;
3392 loader->stack.pop();
3393 break;
3394 }
3395 }
3396
3397 loader->level--;
3398 }
3399
3400
3401 static void _svgLoaderParserXmlOpen(SvgLoaderData* loader, const char* content, unsigned int length, bool empty)
3402 {
3403 const char* attrs = nullptr;
3404 int attrsLength = 0;
3405 int sz = length;
3406 char tagName[20] = "";
3407 FactoryMethod method;
3408 GradientFactoryMethod gradientMethod;
3409 SvgNode *node = nullptr, *parent = nullptr;
3410 loader->level++;
3411 attrs = simpleXmlFindAttributesTag(content, length);
3412
3413 if (!attrs) {
3414 //Parse the empty tag
3415 attrs = content;
3416 while ((attrs != nullptr) && *attrs != '>') attrs++;
3417 if (empty) attrs--;
3418 }
3419
3420 if (attrs) {
3421 //Find out the tag name starting from content till sz length
3422 sz = attrs - content;
3423 while ((sz > 0) && (isspace(content[sz - 1]))) sz--;
3424 if ((unsigned)sz >= sizeof(tagName)) return;
3425 strncpy(tagName, content, sz);
3426 tagName[sz] = '\0';
3427 attrsLength = length - sz;
3428 }
3429
3430 if ((method = _findGroupFactory(tagName))) {
3431 //Group
3432 if (empty) return;
3433 if (!loader->doc) {
3434 if (strcmp(tagName, "svg")) return; //Not a valid svg document
3435 node = method(loader, nullptr, attrs, attrsLength, simpleXmlParseAttributes);
3436 loader->doc = node;
3437 } else {
3438 if (!strcmp(tagName, "svg")) return; //Already loaded <svg>(SvgNodeType::Doc) tag
3439 if (loader->stack.count > 0) parent = loader->stack.last();
3440 else parent = loader->doc;
3441 if (!strcmp(tagName, "style")) {
3442 // TODO: For now only the first style node is saved. After the css id selector
3443 // is introduced this if condition shouldn't be necessary any more
3444 if (!loader->cssStyle) {
3445 node = method(loader, nullptr, attrs, attrsLength, simpleXmlParseAttributes);
3446 loader->cssStyle = node;
3447 loader->doc->node.doc.style = node;
3448 loader->openedTag = OpenedTagType::Style;
3449 }
3450 } else {
3451 node = method(loader, parent, attrs, attrsLength, simpleXmlParseAttributes);
3452 }
3453 }
3454
3455 if (!node) return;
3456 if (node->type != SvgNodeType::Defs || !empty) {
3457 loader->stack.push(node);
3458 }
3459 } else if ((method = _findGraphicsFactory(tagName))) {
3460 if (loader->stack.count > 0) parent = loader->stack.last();
3461 else parent = loader->doc;
3462 node = method(loader, parent, attrs, attrsLength, simpleXmlParseAttributes);
3463 if (node && !empty) {
3464 if (!strcmp(tagName, "text")) loader->openedTag = OpenedTagType::Text;
3465 auto defs = _createDefsNode(loader, nullptr, nullptr, 0, nullptr);
3466 loader->stack.push(defs);
3467 loader->currentGraphicsNode = node;
3468 }
3469 } else if ((gradientMethod = _findGradientFactory(tagName))) {
3470 SvgStyleGradient* gradient;
3471 gradient = gradientMethod(loader, attrs, attrsLength);
3472 //Gradients do not allow nested declarations, so only the earliest declared Gradient is valid.
3473 if (loader->gradientStack.count == 0) {
3474 //FIXME: The current parsing structure does not distinguish end tags.
3475 // There is no way to know if the currently parsed gradient is in defs.
3476 // If a gradient is declared outside of defs after defs is set, it is included in the gradients of defs.
3477 // But finally, the loader has a gradient style list regardless of defs.
3478 // This is only to support this when multiple gradients are declared, even if no defs are declared.
3479 // refer to: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/defs
3480 if (loader->def && loader->doc->node.doc.defs) {
3481 loader->def->node.defs.gradients.push(gradient);
3482 } else {
3483 loader->gradients.push(gradient);
3484 }
3485 }
3486 if (!empty) loader->gradientStack.push(gradient);
3487 } else if (!strcmp(tagName, "stop")) {
3488 if (loader->gradientStack.count == 0) {
3489 TVGLOG("SVG", "Stop element is used outside of the Gradient element");
3490 return;
3491 }
3492 /* default value for opacity */
3493 loader->svgParse->gradStop = {0.0f, 0, 0, 0, 255};
3494 loader->svgParse->flags = SvgStopStyleFlags::StopDefault;
3495 simpleXmlParseAttributes(attrs, attrsLength, _attrParseStops, loader);
3496 loader->gradientStack.last()->stops.push(loader->svgParse->gradStop);
3497 } else {
3498 if (!isIgnoreUnsupportedLogElements(tagName)) TVGLOG("SVG", "Unsupported elements used [Elements: %s]", tagName);
3499 }
3500 }
3501
3502
3503 static void _svgLoaderParserText(SvgLoaderData* loader, const char* content, unsigned int length)
3504 {
3505 auto text = &loader->svgParse->node->node.text;
3506 text->text = strAppend(text->text, content, length);
3507 }
3508
3509
3510 static void _svgLoaderParserXmlCssStyle(SvgLoaderData* loader, const char* content, unsigned int length)
3511 {
3512 char* tag;
3513 char* name;
3514 const char* attrs = nullptr;
3515 unsigned int attrsLength = 0;
3516
3517 FactoryMethod method;
3518 GradientFactoryMethod gradientMethod;
3519 SvgNode *node = nullptr;
3520
3521 while (auto next = simpleXmlParseCSSAttribute(content, length, &tag, &name, &attrs, &attrsLength)) {
3522 if ((method = _findGroupFactory(tag))) {
3523 if ((node = method(loader, loader->cssStyle, attrs, attrsLength, simpleXmlParseW3CAttribute))) node->id = _copyId(name);
3524 } else if ((method = _findGraphicsFactory(tag))) {
3525 if ((node = method(loader, loader->cssStyle, attrs, attrsLength, simpleXmlParseW3CAttribute))) node->id = _copyId(name);
3526 } else if ((gradientMethod = _findGradientFactory(tag))) {
3527 TVGLOG("SVG", "Unsupported elements used in the internal CSS style sheets [Elements: %s]", tag);
3528 } else if (!strcmp(tag, "stop")) {
3529 TVGLOG("SVG", "Unsupported elements used in the internal CSS style sheets [Elements: %s]", tag);
3530 } else if (!strcmp(tag, "all")) {
3531 if ((node = _createCssStyleNode(loader, loader->cssStyle, attrs, attrsLength, simpleXmlParseW3CAttribute))) node->id = _copyId(name);
3532 } else if (!strcmp(tag, "@font-face")) { //css at-rule specifying font
3533 _createFontFace(loader, attrs, attrsLength, simpleXmlParseW3CAttribute);
3534 } else if (!isIgnoreUnsupportedLogElements(tag)) {
3535 TVGLOG("SVG", "Unsupported elements used in the internal CSS style sheets [Elements: %s]", tag);
3536 }
3537
3538 length -= next - content;
3539 content = next;
3540
3541 free(tag);
3542 free(name);
3543 }
3544 loader->openedTag = OpenedTagType::Other;
3545 }
3546
3547
3548 static bool _svgLoaderParser(void* data, SimpleXMLType type, const char* content, unsigned int length)
3549 {
3550 SvgLoaderData* loader = (SvgLoaderData*)data;
3551
3552 switch (type) {
3553 case SimpleXMLType::Open: {
3554 _svgLoaderParserXmlOpen(loader, content, length, false);
3555 break;
3556 }
3557 case SimpleXMLType::OpenEmpty: {
3558 _svgLoaderParserXmlOpen(loader, content, length, true);
3559 break;
3560 }
3561 case SimpleXMLType::Close: {
3562 _svgLoaderParserXmlClose(loader, content, length);
3563 break;
3564 }
3565 case SimpleXMLType::Data:
3566 case SimpleXMLType::CData: {
3567 if (loader->openedTag == OpenedTagType::Style) _svgLoaderParserXmlCssStyle(loader, content, length);
3568 else if (loader->openedTag == OpenedTagType::Text) _svgLoaderParserText(loader, content, length);
3569 break;
3570 }
3571 case SimpleXMLType::DoctypeChild: {
3572 break;
3573 }
3574 case SimpleXMLType::Ignored:
3575 case SimpleXMLType::Comment:
3576 case SimpleXMLType::Doctype: {
3577 break;
3578 }
3579 default: {
3580 break;
3581 }
3582 }
3583
3584 return true;
3585 }
3586
3587
3588 static void _inefficientNodeCheck(TVG_UNUSED SvgNode* node)
3589 {
3590 #ifdef THORVG_LOG_ENABLED
3591 auto type = simpleXmlNodeTypeToString(node->type);
3592
3593 if (!node->style->display && node->type != SvgNodeType::ClipPath) TVGLOG("SVG", "Inefficient elements used [Display is none][Node Type : %s]", type);
3594 if (node->style->opacity == 0) TVGLOG("SVG", "Inefficient elements used [Opacity is zero][Node Type : %s]", type);
3595 if (node->style->fill.opacity == 0 && node->style->stroke.opacity == 0) TVGLOG("SVG", "Inefficient elements used [Fill opacity and stroke opacity are zero][Node Type : %s]", type);
3596
3597 switch (node->type) {
3598 case SvgNodeType::Path: {
3599 if (!node->node.path.path) TVGLOG("SVG", "Inefficient elements used [Empty path][Node Type : %s]", type);
3600 break;
3601 }
3602 case SvgNodeType::Ellipse: {
3603 if (node->node.ellipse.rx == 0 && node->node.ellipse.ry == 0) TVGLOG("SVG", "Inefficient elements used [Size is zero][Node Type : %s]", type);
3604 break;
3605 }
3606 case SvgNodeType::Polygon:
3607 case SvgNodeType::Polyline: {
3608 if (node->node.polygon.pts.count < 2) TVGLOG("SVG", "Inefficient elements used [Invalid Polygon][Node Type : %s]", type);
3609 break;
3610 }
3611 case SvgNodeType::Circle: {
3612 if (node->node.circle.r == 0) TVGLOG("SVG", "Inefficient elements used [Size is zero][Node Type : %s]", type);
3613 break;
3614 }
3615 case SvgNodeType::Rect: {
3616 if (node->node.rect.w == 0 && node->node.rect.h) TVGLOG("SVG", "Inefficient elements used [Size is zero][Node Type : %s]", type);
3617 break;
3618 }
3619 case SvgNodeType::Line: {
3620 if (node->node.line.x1 == node->node.line.x2 && node->node.line.y1 == node->node.line.y2) TVGLOG("SVG", "Inefficient elements used [Size is zero][Node Type : %s]", type);
3621 break;
3622 }
3623 default: break;
3624 }
3625 #endif
3626 }
3627
3628
3629 static void _updateStyle(SvgNode* node, SvgStyleProperty* parentStyle)
3630 {
3631 _styleInherit(node->style, parentStyle);
3632 _inefficientNodeCheck(node);
3633
3634 auto child = node->child.data;
3635 for (uint32_t i = 0; i < node->child.count; ++i, ++child) {
3636 _updateStyle(*child, node->style);
3637 }
3638 }
3639
3640
3641 static SvgStyleGradient* _gradientDup(SvgLoaderData* loader, Array<SvgStyleGradient*>* gradients, const char* id)
3642 {
3643 SvgStyleGradient* result = nullptr;
3644
3645 auto gradList = gradients->data;
3646
3647 for (uint32_t i = 0; i < gradients->count; ++i) {
3648 if ((*gradList)->id && !strcmp((*gradList)->id, id)) {
3649 result = _cloneGradient(*gradList);
3650 break;
3651 }
3652 ++gradList;
3653 }
3654
3655 if (result && result->ref) {
3656 gradList = gradients->data;
3657 for (uint32_t i = 0; i < gradients->count; ++i) {
3658 if ((*gradList)->id && !strcmp((*gradList)->id, result->ref)) {
3659 _inheritGradient(loader, result, *gradList);
3660 break;
3661 }
3662 ++gradList;
3663 }
3664 }
3665
3666 return result;
3667 }
3668
3669
3670 static void _updateGradient(SvgLoaderData* loader, SvgNode* node, Array<SvgStyleGradient*>* gradients)
3671 {
3672 if (node->child.count > 0) {
3673 auto child = node->child.data;
3674 for (uint32_t i = 0; i < node->child.count; ++i, ++child) {
3675 _updateGradient(loader, *child, gradients);
3676 }
3677 } else {
3678 if (node->style->fill.paint.url) {
3679 auto newGrad = _gradientDup(loader, gradients, node->style->fill.paint.url);
3680 if (newGrad) {
3681 if (node->style->fill.paint.gradient) {
3682 node->style->fill.paint.gradient->clear();
3683 free(node->style->fill.paint.gradient);
3684 }
3685 node->style->fill.paint.gradient = newGrad;
3686 }
3687 }
3688 if (node->style->stroke.paint.url) {
3689 auto newGrad = _gradientDup(loader, gradients, node->style->stroke.paint.url);
3690 if (newGrad) {
3691 if (node->style->stroke.paint.gradient) {
3692 node->style->stroke.paint.gradient->clear();
3693 free(node->style->stroke.paint.gradient);
3694 }
3695 node->style->stroke.paint.gradient = newGrad;
3696 }
3697 }
3698 }
3699 }
3700
3701
3702 static void _updateComposite(SvgNode* node, SvgNode* root)
3703 {
3704 if (node->style->clipPath.url && !node->style->clipPath.node) {
3705 SvgNode* findResult = _findNodeById(root, node->style->clipPath.url);
3706 if (findResult) node->style->clipPath.node = findResult;
3707 }
3708 if (node->style->mask.url && !node->style->mask.node) {
3709 SvgNode* findResult = _findNodeById(root, node->style->mask.url);
3710 if (findResult) node->style->mask.node = findResult;
3711 }
3712 if (node->child.count > 0) {
3713 auto child = node->child.data;
3714 for (uint32_t i = 0; i < node->child.count; ++i, ++child) {
3715 _updateComposite(*child, root);
3716 }
3717 }
3718 }
3719
3720
3721 static void _freeNodeStyle(SvgStyleProperty* style)
3722 {
3723 if (!style) return;
3724
3725 //style->clipPath.node and style->mask.node has only the addresses of node. Therefore, node is released from _freeNode.
3726 free(style->clipPath.url);
3727 free(style->mask.url);
3728 free(style->cssClass);
3729
3730 if (style->fill.paint.gradient) {
3731 style->fill.paint.gradient->clear();
3732 free(style->fill.paint.gradient);
3733 }
3734 if (style->stroke.paint.gradient) {
3735 style->stroke.paint.gradient->clear();
3736 free(style->stroke.paint.gradient);
3737 }
3738 free(style->fill.paint.url);
3739 free(style->stroke.paint.url);
3740 style->stroke.dash.array.reset();
3741 free(style);
3742 }
3743
3744
3745 static void _freeNode(SvgNode* node)
3746 {
3747 if (!node) return;
3748
3749 auto child = node->child.data;
3750 for (uint32_t i = 0; i < node->child.count; ++i, ++child) {
3751 _freeNode(*child);
3752 }
3753 node->child.reset();
3754
3755 free(node->id);
3756 free(node->transform);
3757 _freeNodeStyle(node->style);
3758 switch (node->type) {
3759 case SvgNodeType::Path: {
3760 free(node->node.path.path);
3761 break;
3762 }
3763 case SvgNodeType::Polygon: {
3764 free(node->node.polygon.pts.data);
3765 break;
3766 }
3767 case SvgNodeType::Polyline: {
3768 free(node->node.polyline.pts.data);
3769 break;
3770 }
3771 case SvgNodeType::Doc: {
3772 _freeNode(node->node.doc.defs);
3773 _freeNode(node->node.doc.style);
3774 break;
3775 }
3776 case SvgNodeType::Defs: {
3777 auto gradients = node->node.defs.gradients.data;
3778 for (size_t i = 0; i < node->node.defs.gradients.count; ++i) {
3779 (*gradients)->clear();
3780 free(*gradients);
3781 ++gradients;
3782 }
3783 node->node.defs.gradients.reset();
3784 break;
3785 }
3786 case SvgNodeType::Image: {
3787 free(node->node.image.href);
3788 break;
3789 }
3790 case SvgNodeType::Text: {
3791 free(node->node.text.text);
3792 free(node->node.text.fontFamily);
3793 break;
3794 }
3795 default: {
3796 break;
3797 }
3798 }
3799 free(node);
3800 }
3801
3802
3803 static bool _svgLoaderParserForValidCheckXmlOpen(SvgLoaderData* loader, const char* content, unsigned int length)
3804 {
3805 const char* attrs = nullptr;
3806 int sz = length;
3807 char tagName[20] = "";
3808 FactoryMethod method;
3809 SvgNode *node = nullptr;
3810 int attrsLength = 0;
3811 loader->level++;
3812 attrs = simpleXmlFindAttributesTag(content, length);
3813
3814 if (!attrs) {
3815 //Parse the empty tag
3816 attrs = content;
3817 while ((attrs != nullptr) && *attrs != '>') attrs++;
3818 }
3819
3820 if (attrs) {
3821 sz = attrs - content;
3822 while ((sz > 0) && (isspace(content[sz - 1]))) sz--;
3823 if ((unsigned)sz >= sizeof(tagName)) return false;
3824 strncpy(tagName, content, sz);
3825 tagName[sz] = '\0';
3826 attrsLength = length - sz;
3827 }
3828
3829 if ((method = _findGroupFactory(tagName))) {
3830 if (!loader->doc) {
3831 if (strcmp(tagName, "svg")) return true; //Not a valid svg document
3832 node = method(loader, nullptr, attrs, attrsLength, simpleXmlParseAttributes);
3833 loader->doc = node;
3834 loader->stack.push(node);
3835 return false;
3836 }
3837 }
3838 return true;
3839 }
3840
3841
3842 static bool _svgLoaderParserForValidCheck(void* data, SimpleXMLType type, const char* content, unsigned int length)
3843 {
3844 SvgLoaderData* loader = (SvgLoaderData*)data;
3845 bool res = true;;
3846
3847 switch (type) {
3848 case SimpleXMLType::Open:
3849 case SimpleXMLType::OpenEmpty: {
3850 //If 'res' is false, it means <svg> tag is found.
3851 res = _svgLoaderParserForValidCheckXmlOpen(loader, content, length);
3852 break;
3853 }
3854 default: {
3855 break;
3856 }
3857 }
3858
3859 return res;
3860 }
3861
3862
3863 void SvgLoader::clear(bool all)
3864 {
3865 //flush out the intermediate data
3866 free(loaderData.svgParse);
3867 loaderData.svgParse = nullptr;
3868
3869 for (auto gradient = loaderData.gradients.begin(); gradient < loaderData.gradients.end(); ++gradient) {
3870 (*gradient)->clear();
3871 free(*gradient);
3872 }
3873 loaderData.gradients.reset();
3874
3875 _freeNode(loaderData.doc);
3876 loaderData.doc = nullptr;
3877 loaderData.stack.reset();
3878
3879 if (!all) return;
3880
3881 for (auto p = loaderData.images.begin(); p < loaderData.images.end(); ++p) {
3882 free(*p);
3883 }
3884 loaderData.images.reset();
3885
3886 if (copy) free((char*)content);
3887
3888 delete(root);
3889 root = nullptr;
3890
3891 size = 0;
3892 content = nullptr;
3893 copy = false;
3894 }
3895
3896
3897 /************************************************************************/
3898 /* External Class Implementation */
3899 /************************************************************************/
3900
3901 SvgLoader::SvgLoader() : ImageLoader(FileType::Svg)
3902 {
3903 }
3904
3905
3906 SvgLoader::~SvgLoader()
3907 {
3908 done();
3909 clear();
3910 }
3911
3912
3913 void SvgLoader::run(unsigned tid)
3914 {
3915 //According to the SVG standard the value of the width/height of the viewbox set to 0 disables rendering
3916 if ((viewFlag & SvgViewFlag::Viewbox) && (fabsf(vw) <= FLOAT_EPSILON || fabsf(vh) <= FLOAT_EPSILON)) {
3917 TVGLOG("SVG", "The <viewBox> width and/or height set to 0 - rendering disabled.");
3918 root = Scene::gen().release();
3919 return;
3920 }
3921
3922 if (!simpleXmlParse(content, size, true, _svgLoaderParser, &(loaderData))) return;
3923
3924 if (loaderData.doc) {
3925 auto defs = loaderData.doc->node.doc.defs;
3926
3927 if (loaderData.nodesToStyle.count > 0) cssApplyStyleToPostponeds(loaderData.nodesToStyle, loaderData.cssStyle);
3928 if (loaderData.cssStyle) cssUpdateStyle(loaderData.doc, loaderData.cssStyle);
3929
3930 if (!loaderData.cloneNodes.empty()) _clonePostponedNodes(&loaderData.cloneNodes, loaderData.doc);
3931
3932 _updateComposite(loaderData.doc, loaderData.doc);
3933 if (defs) _updateComposite(loaderData.doc, defs);
3934
3935 _updateStyle(loaderData.doc, nullptr);
3936 if (defs) _updateStyle(defs, nullptr);
3937
3938 if (loaderData.gradients.count > 0) _updateGradient(&loaderData, loaderData.doc, &loaderData.gradients);
3939 if (defs) _updateGradient(&loaderData, loaderData.doc, &defs->node.defs.gradients);
3940 }
3941 root = svgSceneBuild(loaderData, {vx, vy, vw, vh}, w, h, align, meetOrSlice, svgPath, viewFlag);
3942
3943 //In case no viewbox and width/height data is provided the completion of loading
3944 //has to be forced, in order to establish this data based on the whole picture.
3945 if (!(viewFlag & SvgViewFlag::Viewbox)) {
3946 //Override viewbox & size again after svg loading.
3947 vx = loaderData.doc->node.doc.vx;
3948 vy = loaderData.doc->node.doc.vy;
3949 vw = loaderData.doc->node.doc.vw;
3950 vh = loaderData.doc->node.doc.vh;
3951 w = loaderData.doc->node.doc.w;
3952 h = loaderData.doc->node.doc.h;
3953 }
3954
3955 clear(false);
3956 }
3957
3958
3959 bool SvgLoader::header()
3960 {
3961 //For valid check, only <svg> tag is parsed first.
3962 //If the <svg> tag is found, the loaded file is valid and stores viewbox information.
3963 //After that, the remaining content data is parsed in order with async.
3964 loaderData.svgParse = (SvgParser*)malloc(sizeof(SvgParser));
3965 if (!loaderData.svgParse) return false;
3966
3967 loaderData.svgParse->flags = SvgStopStyleFlags::StopDefault;
3968 viewFlag = SvgViewFlag::None;
3969
3970 simpleXmlParse(content, size, true, _svgLoaderParserForValidCheck, &(loaderData));
3971
3972 if (loaderData.doc && loaderData.doc->type == SvgNodeType::Doc) {
3973 viewFlag = loaderData.doc->node.doc.viewFlag;
3974 align = loaderData.doc->node.doc.align;
3975 meetOrSlice = loaderData.doc->node.doc.meetOrSlice;
3976
3977 if (viewFlag & SvgViewFlag::Viewbox) {
3978 vx = loaderData.doc->node.doc.vx;
3979 vy = loaderData.doc->node.doc.vy;
3980 vw = loaderData.doc->node.doc.vw;
3981 vh = loaderData.doc->node.doc.vh;
3982
3983 if (viewFlag & SvgViewFlag::Width) w = loaderData.doc->node.doc.w;
3984 else {
3985 w = loaderData.doc->node.doc.vw;
3986 if (viewFlag & SvgViewFlag::WidthInPercent) {
3987 w *= loaderData.doc->node.doc.w;
3988 viewFlag = (viewFlag ^ SvgViewFlag::WidthInPercent);
3989 }
3990 viewFlag = (viewFlag | SvgViewFlag::Width);
3991 }
3992 if (viewFlag & SvgViewFlag::Height) h = loaderData.doc->node.doc.h;
3993 else {
3994 h = loaderData.doc->node.doc.vh;
3995 if (viewFlag & SvgViewFlag::HeightInPercent) {
3996 h *= loaderData.doc->node.doc.h;
3997 viewFlag = (viewFlag ^ SvgViewFlag::HeightInPercent);
3998 }
3999 viewFlag = (viewFlag | SvgViewFlag::Height);
4000 }
4001 //In case no viewbox and width/height data is provided the completion of loading
4002 //has to be forced, in order to establish this data based on the whole picture.
4003 } else {
4004 //Before loading, set default viewbox & size if they are empty
4005 vx = vy = 0.0f;
4006 if (viewFlag & SvgViewFlag::Width) {
4007 vw = w = loaderData.doc->node.doc.w;
4008 } else {
4009 vw = 1.0f;
4010 if (viewFlag & SvgViewFlag::WidthInPercent) {
4011 w = loaderData.doc->node.doc.w;
4012 } else w = 1.0f;
4013 }
4014
4015 if (viewFlag & SvgViewFlag::Height) {
4016 vh = h = loaderData.doc->node.doc.h;
4017 } else {
4018 vh = 1.0f;
4019 if (viewFlag & SvgViewFlag::HeightInPercent) {
4020 h = loaderData.doc->node.doc.h;
4021 } else h = 1.0f;
4022 }
4023
4024 run(0);
4025 }
4026
4027 return true;
4028 }
4029
4030 TVGLOG("SVG", "No SVG File. There is no <svg/>");
4031 return false;
4032 }
4033
4034
4035 bool SvgLoader::open(const char* data, uint32_t size, bool copy)
4036 {
4037 clear();
4038
4039 if (copy) {
4040 content = (char*)malloc(size + 1);
4041 if (!content) return false;
4042 memcpy((char*)content, data, size);
4043 content[size] = '\0';
4044 } else content = (char*)data;
4045
4046 this->size = size;
4047 this->copy = copy;
4048
4049 return header();
4050 }
4051
4052
4053 bool SvgLoader::open(const string& path)
4054 {
4055 #ifdef THORVG_FILE_IO_SUPPORT
4056 clear();
4057
4058 ifstream f;
4059 f.open(path);
4060
4061 if (!f.is_open()) return false;
4062
4063 svgPath = path;
4064 getline(f, filePath, '\0');
4065 f.close();
4066
4067 if (filePath.empty()) return false;
4068
4069 content = (char*)filePath.c_str();
4070 size = filePath.size();
4071
4072 return header();
4073 #else
4074 return false;
4075 #endif
4076 }
4077
4078
4079 bool SvgLoader::resize(Paint* paint, float w, float h)
4080 {
4081 if (!paint) return false;
4082
4083 auto sx = w / this->w;
4084 auto sy = h / this->h;
4085 Matrix m = {sx, 0, 0, 0, sy, 0, 0, 0, 1};
4086 paint->transform(m);
4087
4088 return true;
4089 }
4090
4091
4092 bool SvgLoader::read()
4093 {
4094 if (!content || size == 0) return false;
4095
4096 //the loading has been already completed in header()
4097 if (root || !LoadModule::read()) return true;
4098
4099 TaskScheduler::request(this);
4100
4101 return true;
4102 }
4103
4104
4105 bool SvgLoader::close()
4106 {
4107 if (!LoadModule::close()) return false;
4108 this->done();
4109 clear();
4110 return true;
4111 }
4112
4113
4114 Paint* SvgLoader::paint()
4115 {
4116 this->done();
4117 auto ret = root;
4118 root = nullptr;
4119 return ret;
4120 }