2 * Copyright (c) 2020-2021 Samsung Electronics Co., Ltd. All rights reserved.
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:
11 * The above copyright notice and this permission notice shall be included in all
12 * copies or substantial portions of the Software.
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
24 * Copyright notice for the EFL:
26 * Copyright (C) EFL developers (see AUTHORS)
28 * All rights reserved.
30 * Redistribution and use in source and binary forms, with or without
31 * modification, are permitted provided that the following conditions are met:
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.
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.
54 #include "tvgSvgLoaderCommon.h"
55 #include "tvgSvgSceneBuilder.h"
56 #include "tvgSvgPath.h"
57 #include "tvgSvgUtil.h"
59 /************************************************************************/
60 /* Internal Class Implementation */
61 /************************************************************************/
69 static bool _appendShape(SvgNode* node, Shape* shape, const Box& vBox, const string& svgPath);
70 static unique_ptr<Scene> _sceneBuildHelper(const SvgNode* node, const Box& vBox, const string& svgPath, bool mask);
73 static inline bool _isGroupType(SvgNodeType type)
75 if (type == SvgNodeType::Doc || type == SvgNodeType::G || type == SvgNodeType::Use || type == SvgNodeType::ClipPath) return true;
80 //According to: https://www.w3.org/TR/SVG11/coords.html#ObjectBoundingBoxUnits (the last paragraph)
81 //a stroke width should be ignored for bounding box calculations
82 static Box _boundingBox(const Shape* shape)
85 shape->bounds(&x, &y, &w, &h, false);
87 if (auto strokeW = shape->strokeWidth()) {
98 static void _transformMultiply(const Matrix* mBBox, Matrix* gradTransf)
100 gradTransf->e13 = gradTransf->e13 * mBBox->e11 + mBBox->e13;
101 gradTransf->e12 *= mBBox->e11;
102 gradTransf->e11 *= mBBox->e11;
104 gradTransf->e23 = gradTransf->e23 * mBBox->e22 + mBBox->e23;
105 gradTransf->e22 *= mBBox->e22;
106 gradTransf->e21 *= mBBox->e22;
110 static unique_ptr<LinearGradient> _applyLinearGradientProperty(SvgStyleGradient* g, const Shape* vg, const Box& vBox, int opacity)
112 Fill::ColorStop* stops;
114 auto fillGrad = LinearGradient::gen();
116 bool isTransform = (g->transform ? true : false);
117 Matrix finalTransform = {1, 0, 0, 0, 1, 0, 0, 0, 1};
118 if (isTransform) finalTransform = *g->transform;
121 g->linear->x1 = g->linear->x1 * vBox.w;
122 g->linear->y1 = g->linear->y1 * vBox.h;
123 g->linear->x2 = g->linear->x2 * vBox.w;
124 g->linear->y2 = g->linear->y2 * vBox.h;
126 Matrix m = {vBox.w, 0, vBox.x, 0, vBox.h, vBox.y, 0, 0, 1};
127 if (isTransform) _transformMultiply(&m, &finalTransform);
134 if (isTransform) fillGrad->transform(finalTransform);
136 fillGrad->linear(g->linear->x1, g->linear->y1, g->linear->x2, g->linear->y2);
137 fillGrad->spread(g->spread);
140 stopCount = g->stops.count;
142 stops = (Fill::ColorStop*)calloc(stopCount, sizeof(Fill::ColorStop));
143 if (!stops) return fillGrad;
144 auto prevOffset = 0.0f;
145 for (uint32_t i = 0; i < g->stops.count; ++i) {
146 auto colorStop = &g->stops.data[i];
147 //Use premultiplied color
148 stops[i].r = colorStop->r;
149 stops[i].g = colorStop->g;
150 stops[i].b = colorStop->b;
151 stops[i].a = static_cast<uint8_t>((colorStop->a * opacity) / 255);
152 stops[i].offset = colorStop->offset;
153 //check the offset corner cases - refer to: https://svgwg.org/svg2-draft/pservers.html#StopNotes
154 if (colorStop->offset < prevOffset) stops[i].offset = prevOffset;
155 else if (colorStop->offset > 1) stops[i].offset = 1;
156 prevOffset = stops[i].offset;
158 fillGrad->colorStops(stops, stopCount);
165 static unique_ptr<RadialGradient> _applyRadialGradientProperty(SvgStyleGradient* g, const Shape* vg, const Box& vBox, int opacity)
167 Fill::ColorStop *stops;
169 auto fillGrad = RadialGradient::gen();
171 bool isTransform = (g->transform ? true : false);
172 Matrix finalTransform = {1, 0, 0, 0, 1, 0, 0, 0, 1};
173 if (isTransform) finalTransform = *g->transform;
176 //The radius scalling is done according to the Units section:
177 //https://www.w3.org/TR/2015/WD-SVG2-20150915/coords.html
178 g->radial->cx = g->radial->cx * vBox.w;
179 g->radial->cy = g->radial->cy * vBox.h;
180 g->radial->r = g->radial->r * sqrtf(powf(vBox.w, 2.0f) + powf(vBox.h, 2.0f)) / sqrtf(2.0f);
181 g->radial->fx = g->radial->fx * vBox.w;
182 g->radial->fy = g->radial->fy * vBox.h;
184 Matrix m = {vBox.w, 0, vBox.x, 0, vBox.h, vBox.y, 0, 0, 1};
185 if (isTransform) _transformMultiply(&m, &finalTransform);
192 if (isTransform) fillGrad->transform(finalTransform);
194 //TODO: Tvg is not support to focal
195 //if (g->radial->fx != 0 && g->radial->fy != 0) {
196 // fillGrad->radial(g->radial->fx, g->radial->fy, g->radial->r);
198 fillGrad->radial(g->radial->cx, g->radial->cy, g->radial->r);
199 fillGrad->spread(g->spread);
202 stopCount = g->stops.count;
204 stops = (Fill::ColorStop*)calloc(stopCount, sizeof(Fill::ColorStop));
205 if (!stops) return fillGrad;
206 auto prevOffset = 0.0f;
207 for (uint32_t i = 0; i < g->stops.count; ++i) {
208 auto colorStop = &g->stops.data[i];
209 //Use premultiplied color
210 stops[i].r = colorStop->r;
211 stops[i].g = colorStop->g;
212 stops[i].b = colorStop->b;
213 stops[i].a = static_cast<uint8_t>((colorStop->a * opacity) / 255);
214 stops[i].offset = colorStop->offset;
215 //check the offset corner cases - refer to: https://svgwg.org/svg2-draft/pservers.html#StopNotes
216 if (colorStop->offset < prevOffset) stops[i].offset = prevOffset;
217 else if (colorStop->offset > 1) stops[i].offset = 1;
218 prevOffset = stops[i].offset;
220 fillGrad->colorStops(stops, stopCount);
227 static bool _appendChildShape(SvgNode* node, Shape* shape, const Box& vBox, const string& svgPath)
231 if (_appendShape(node, shape, vBox, svgPath)) valid = true;
233 if (node->child.count > 0) {
234 auto child = node->child.data;
235 for (uint32_t i = 0; i < node->child.count; ++i, ++child) {
236 if (_appendChildShape(*child, shape, vBox, svgPath)) valid = true;
244 static void _applyComposition(Paint* paint, const SvgNode* node, const Box& vBox, const string& svgPath)
247 /* Do not drop in Circular Dependency for ClipPath.
248 Composition can be applied recursively if its children nodes have composition target to this one. */
249 if (node->style->clipPath.applying) {
250 TVGLOG("SVG", "Multiple Composition Tried! Check out Circular dependency?");
252 auto compNode = node->style->clipPath.node;
253 if (compNode && compNode->child.count > 0) {
254 node->style->clipPath.applying = true;
256 auto comp = Shape::gen();
257 comp->fill(255, 255, 255, 255);
258 if (node->transform) comp->transform(*node->transform);
260 auto child = compNode->child.data;
261 auto valid = false; //Composite only when valid shapes are existed
263 for (uint32_t i = 0; i < compNode->child.count; ++i, ++child) {
264 if (_appendChildShape(*child, comp.get(), vBox, svgPath)) valid = true;
267 if (valid) paint->composite(move(comp), CompositeMethod::ClipPath);
269 node->style->clipPath.applying = false;
274 /* Do not drop in Circular Dependency for Mask.
275 Composition can be applied recursively if its children nodes have composition target to this one. */
276 if (node->style->mask.applying) {
277 TVGLOG("SVG", "Multiple Composition Tried! Check out Circular dependency?");
279 auto compNode = node->style->mask.node;
280 if (compNode && compNode->child.count > 0) {
281 node->style->mask.applying = true;
283 auto comp = _sceneBuildHelper(compNode, vBox, svgPath, true);
285 if (node->transform) comp->transform(*node->transform);
286 paint->composite(move(comp), CompositeMethod::AlphaMask);
289 node->style->mask.applying = false;
295 static void _applyProperty(SvgNode* node, Shape* vg, const Box& vBox, const string& svgPath)
297 SvgStyleProperty* style = node->style;
299 if (node->transform) vg->transform(*node->transform);
300 if (node->type == SvgNodeType::Doc || !node->display) return;
302 //If fill property is nullptr then do nothing
303 if (style->fill.paint.none) {
305 } else if (style->fill.paint.gradient) {
307 if (!style->fill.paint.gradient->userSpace) bBox = _boundingBox(vg);
309 if (style->fill.paint.gradient->type == SvgGradientType::Linear) {
310 auto linear = _applyLinearGradientProperty(style->fill.paint.gradient, vg, bBox, style->fill.opacity);
311 vg->fill(move(linear));
312 } else if (style->fill.paint.gradient->type == SvgGradientType::Radial) {
313 auto radial = _applyRadialGradientProperty(style->fill.paint.gradient, vg, bBox, style->fill.opacity);
314 vg->fill(move(radial));
316 } else if (style->fill.paint.url) {
317 //TODO: Apply the color pointed by url
318 } else if (style->fill.paint.curColor) {
319 //Apply the current style color
320 vg->fill(style->color.r, style->color.g, style->color.b, style->fill.opacity);
322 //Apply the fill color
323 vg->fill(style->fill.paint.color.r, style->fill.paint.color.g, style->fill.paint.color.b, style->fill.opacity);
326 //Apply the fill rule
327 vg->fill((tvg::FillRule)style->fill.fillRule);
330 if (style->opacity < 255) vg->opacity(style->opacity);
332 if (node->type == SvgNodeType::G || node->type == SvgNodeType::Use) return;
334 //Apply the stroke style property
335 vg->stroke(style->stroke.width);
336 vg->stroke(style->stroke.cap);
337 vg->stroke(style->stroke.join);
338 if (style->stroke.dash.array.count > 0) {
339 vg->stroke(style->stroke.dash.array.data, style->stroke.dash.array.count);
342 //If stroke property is nullptr then do nothing
343 if (style->stroke.paint.none) {
345 } else if (style->stroke.paint.gradient) {
347 if (!style->stroke.paint.gradient->userSpace) bBox = _boundingBox(vg);
349 if (style->stroke.paint.gradient->type == SvgGradientType::Linear) {
350 auto linear = _applyLinearGradientProperty(style->stroke.paint.gradient, vg, bBox, style->stroke.opacity);
351 vg->stroke(move(linear));
352 } else if (style->stroke.paint.gradient->type == SvgGradientType::Radial) {
353 auto radial = _applyRadialGradientProperty(style->stroke.paint.gradient, vg, bBox, style->stroke.opacity);
354 vg->stroke(move(radial));
356 } else if (style->stroke.paint.url) {
357 //TODO: Apply the color pointed by url
358 } else if (style->stroke.paint.curColor) {
359 //Apply the current style color
360 vg->stroke(style->color.r, style->color.g, style->color.b, style->stroke.opacity);
362 //Apply the stroke color
363 vg->stroke(style->stroke.paint.color.r, style->stroke.paint.color.g, style->stroke.paint.color.b, style->stroke.opacity);
366 _applyComposition(vg, node, vBox, svgPath);
370 static unique_ptr<Shape> _shapeBuildHelper(SvgNode* node, const Box& vBox, const string& svgPath)
372 auto shape = Shape::gen();
373 if (_appendShape(node, shape.get(), vBox, svgPath)) return shape;
378 static bool _appendShape(SvgNode* node, Shape* shape, const Box& vBox, const string& svgPath)
380 Array<PathCommand> cmds;
383 switch (node->type) {
384 case SvgNodeType::Path: {
385 if (node->node.path.path) {
386 if (svgPathToTvgPath(node->node.path.path, cmds, pts)) {
387 shape->appendPath(cmds.data, cmds.count, pts.data, pts.count);
392 case SvgNodeType::Ellipse: {
393 shape->appendCircle(node->node.ellipse.cx, node->node.ellipse.cy, node->node.ellipse.rx, node->node.ellipse.ry);
396 case SvgNodeType::Polygon: {
397 if (node->node.polygon.pointsCount < 2) break;
398 shape->moveTo(node->node.polygon.points[0], node->node.polygon.points[1]);
399 for (int i = 2; i < node->node.polygon.pointsCount - 1; i += 2) {
400 shape->lineTo(node->node.polygon.points[i], node->node.polygon.points[i + 1]);
405 case SvgNodeType::Polyline: {
406 if (node->node.polygon.pointsCount < 2) break;
407 shape->moveTo(node->node.polygon.points[0], node->node.polygon.points[1]);
408 for (int i = 2; i < node->node.polygon.pointsCount - 1; i += 2) {
409 shape->lineTo(node->node.polygon.points[i], node->node.polygon.points[i + 1]);
413 case SvgNodeType::Circle: {
414 shape->appendCircle(node->node.circle.cx, node->node.circle.cy, node->node.circle.r, node->node.circle.r);
417 case SvgNodeType::Rect: {
418 shape->appendRect(node->node.rect.x, node->node.rect.y, node->node.rect.w, node->node.rect.h, node->node.rect.rx, node->node.rect.ry);
421 case SvgNodeType::Line: {
422 shape->moveTo(node->node.line.x1, node->node.line.y1);
423 shape->lineTo(node->node.line.x2, node->node.line.y2);
431 _applyProperty(node, shape, vBox, svgPath);
436 enum class imageMimeTypeEncoding
441 constexpr imageMimeTypeEncoding operator|(imageMimeTypeEncoding a, imageMimeTypeEncoding b) {
442 return static_cast<imageMimeTypeEncoding>(static_cast<int>(a) | static_cast<int>(b));
444 constexpr bool operator&(imageMimeTypeEncoding a, imageMimeTypeEncoding b) {
445 return (static_cast<int>(a) & static_cast<int>(b));
449 static constexpr struct
453 imageMimeTypeEncoding encoding;
454 } imageMimeTypes[] = {
455 {"jpeg", sizeof("jpeg"), imageMimeTypeEncoding::base64},
456 {"png", sizeof("png"), imageMimeTypeEncoding::base64},
457 {"svg+xml", sizeof("svg+xml"), imageMimeTypeEncoding::base64 | imageMimeTypeEncoding::utf8},
461 static bool _isValidImageMimeTypeAndEncoding(const char** href, const char** mimetype, imageMimeTypeEncoding* encoding) {
462 if (strncmp(*href, "image/", sizeof("image/") - 1)) return false; //not allowed mime type
463 *href += sizeof("image/") - 1;
465 //RFC2397 data:[<mediatype>][;base64],<data>
466 //mediatype := [ type "/" subtype ] *( ";" parameter )
467 //parameter := attribute "=" value
468 for (unsigned int i = 0; i < sizeof(imageMimeTypes) / sizeof(imageMimeTypes[0]); i++) {
469 if (!strncmp(*href, imageMimeTypes[i].name, imageMimeTypes[i].sz - 1)) {
470 *href += imageMimeTypes[i].sz - 1;
471 *mimetype = imageMimeTypes[i].name;
473 while (**href && **href != ',') {
474 while (**href && **href != ';') ++(*href);
475 if (!**href) return false;
478 if (imageMimeTypes[i].encoding & imageMimeTypeEncoding::base64) {
479 if (!strncmp(*href, "base64,", sizeof("base64,") - 1)) {
480 *href += sizeof("base64,") - 1;
481 *encoding = imageMimeTypeEncoding::base64;
482 return true; //valid base64
485 if (imageMimeTypes[i].encoding & imageMimeTypeEncoding::utf8) {
486 if (!strncmp(*href, "utf8,", sizeof("utf8,") - 1)) {
487 *href += sizeof("utf8,") - 1;
488 *encoding = imageMimeTypeEncoding::utf8;
489 return true; //valid utf8
493 //no encoding defined
494 if (**href == ',' && (imageMimeTypes[i].encoding & imageMimeTypeEncoding::utf8)) {
496 *encoding = imageMimeTypeEncoding::utf8;
497 return true; //allow no encoding defined if utf8 expected
506 static unique_ptr<Picture> _imageBuildHelper(SvgNode* node, const Box& vBox, const string& svgPath)
508 if (!node->node.image.href) return nullptr;
509 auto picture = Picture::gen();
511 const char* href = node->node.image.href;
512 if (!strncmp(href, "data:", sizeof("data:") - 1)) {
513 href += sizeof("data:") - 1;
514 const char* mimetype;
515 imageMimeTypeEncoding encoding;
516 if (!_isValidImageMimeTypeAndEncoding(&href, &mimetype, &encoding)) return nullptr; //not allowed mime type or encoding
517 if (encoding == imageMimeTypeEncoding::base64) {
518 string decoded = svgUtilBase64Decode(href);
519 if (picture->load(decoded.c_str(), decoded.size(), mimetype, true) != Result::Success) return nullptr;
521 string decoded = svgUtilURLDecode(href);
522 if (picture->load(decoded.c_str(), decoded.size(), mimetype, true) != Result::Success) return nullptr;
525 if (!strncmp(href, "file://", sizeof("file://") - 1)) href += sizeof("file://") - 1;
526 //TODO: protect against recursive svg image loading
527 //Temporarily disable embedded svg:
528 const char *dot = strrchr(href, '.');
529 if (dot && !strcmp(dot, ".svg")) {
530 TVGLOG("SVG", "Embedded svg file is disabled.");
533 string imagePath = href;
534 if (strncmp(href, "/", 1)) {
535 auto last = svgPath.find_last_of("/");
536 imagePath = svgPath.substr(0, (last == string::npos ? 0 : last + 1 )) + imagePath;
538 if (picture->load(imagePath) != Result::Success) return nullptr;
542 if (picture->size(&w, &h) == Result::Success && w > 0 && h > 0) {
543 auto sx = node->node.image.w / w;
544 auto sy = node->node.image.h / h;
545 Matrix m = {sx, 0, node->node.image.x, 0, sy, node->node.image.y, 0, 0, 1};
546 picture->transform(m);
549 _applyComposition(picture.get(), node, vBox, svgPath);
554 static unique_ptr<Scene> _useBuildHelper(const SvgNode* node, const Box& vBox, const string& svgPath)
556 auto scene = _sceneBuildHelper(node, vBox, svgPath, false);
557 if (node->node.use.x != 0.0f || node->node.use.y != 0.0f) {
558 scene->translate(node->node.use.x, node->node.use.y);
560 if (node->node.use.w > 0.0f && node->node.use.h > 0.0f) {
561 //TODO: handle width/height properties
567 static unique_ptr<Scene> _sceneBuildHelper(const SvgNode* node, const Box& vBox, const string& svgPath, bool mask)
569 if (_isGroupType(node->type) || mask) {
570 auto scene = Scene::gen();
571 if (!mask && node->transform) scene->transform(*node->transform);
573 if (node->display && node->style->opacity != 0) {
574 auto child = node->child.data;
575 for (uint32_t i = 0; i < node->child.count; ++i, ++child) {
576 if (_isGroupType((*child)->type)) {
577 if ((*child)->type == SvgNodeType::Use)
578 scene->push(_useBuildHelper(*child, vBox, svgPath));
580 scene->push(_sceneBuildHelper(*child, vBox, svgPath, false));
581 } else if ((*child)->type == SvgNodeType::Image) {
582 auto image = _imageBuildHelper(*child, vBox, svgPath);
583 if (image) scene->push(move(image));
584 } else if ((*child)->type != SvgNodeType::Mask) {
585 auto shape = _shapeBuildHelper(*child, vBox, svgPath);
586 if (shape) scene->push(move(shape));
589 _applyComposition(scene.get(), node, vBox, svgPath);
590 scene->opacity(node->style->opacity);
598 /************************************************************************/
599 /* External Class Implementation */
600 /************************************************************************/
602 unique_ptr<Scene> svgSceneBuild(SvgNode* node, float vx, float vy, float vw, float vh, float w, float h, bool preserveAspect, const string& svgPath)
604 if (!node || (node->type != SvgNodeType::Doc)) return nullptr;
606 Box vBox = {vx, vy, vw, vh};
607 auto docNode = _sceneBuildHelper(node, vBox, svgPath, false);
609 if (!mathEqual(w, vw) || !mathEqual(h, vh)) {
613 if (preserveAspect) {
615 auto scale = sx < sy ? sx : sy;
616 docNode->scale(scale);
618 auto tvx = vx * scale;
619 auto tvy = vy * scale;
620 auto tvw = vw * scale;
621 auto tvh = vh * scale;
622 if (vw > vh) tvy -= (h - tvh) * 0.5f;
623 else tvx -= (w - tvw) * 0.5f;
624 docNode->translate(-tvx, -tvy);
631 if (tvw > tvh) tvy -= (h - tvh) * 0.5f;
632 else tvx -= (w - tvw) * 0.5f;
633 Matrix m = {sx, 0, -tvx, 0, sy, -tvy, 0, 0, 1};
634 docNode->transform(m);
636 } else if (!mathZero(vx) || !mathZero(vy)) {
637 docNode->translate(-vx, -vy);
640 auto viewBoxClip = Shape::gen();
641 viewBoxClip->appendRect(0, 0, w, h, 0, 0);
642 viewBoxClip->fill(0, 0, 0, 255);
644 auto compositeLayer = Scene::gen();
645 compositeLayer->composite(move(viewBoxClip), CompositeMethod::ClipPath);
646 compositeLayer->push(move(docNode));
648 auto root = Scene::gen();
649 root->push(move(compositeLayer));