SVG for C++
Loading...
Searching...
No Matches
svg.hpp
Go to the documentation of this file.
1/*
2 ____ __ ______
3 / ___|\ \ / / ___|
4 \___ \ \ \ / / | _
5 ___) | \ V /| |_| |
6 |____/ \_/ \____|
7
8 SVG for C++ v0.5.1
9
10 Copyright (c) 2018-2026 Vincent La
11 SPDX-License-Identifier: MIT
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
33#pragma once
34#define PI 3.14159265
35#define RAD_TO_DEG (180/PI)
36#define SVG_TYPE_CHECK static_assert(std::is_base_of<Element, T>::value, "Child must be an SVG element.")
37#define APPROX_EQUALS(x, y, tol) bool(abs(x - y) < tol)
38#include <iostream>
39#include <algorithm> // min, max
40#include <cctype>
41#include <cmath>
42#include <cstdint>
43#include <fstream> // ofstream
44#include <functional>
45#include <math.h> // NAN
46#include <map>
47#include <deque>
48#include <set>
49#include <vector>
50#include <string>
51#include <sstream> // stringstream
52#include <iomanip> // setprecision
53#include <iterator>
54#include <memory>
55#include <stdexcept>
56#include <type_traits> // is_base_of
57#include <tuple>
58#include <utility>
59
60namespace SVG {
64 class AttributeMap;
65 class Element;
66 class LinearGradient;
67 class RadialGradient;
68 class SVG;
69 class Shape;
70 class Symbol;
71 class Use;
72
74 enum class ElementKind {
75 Custom,
76 Defs,
79 Stop,
80 Symbol,
81 Use,
82 SVG,
83 Style,
84 Path,
85 Text,
86 Title,
87 Group,
88 Line,
89 Rect,
90 Circle,
92 };
93
95 inline std::string tag_name(ElementKind kind) {
96 switch (kind) {
97 case ElementKind::Defs: return "defs";
98 case ElementKind::LinearGradient: return "linearGradient";
99 case ElementKind::RadialGradient: return "radialGradient";
100 case ElementKind::Stop: return "stop";
101 case ElementKind::Symbol: return "symbol";
102 case ElementKind::Use: return "use";
103 case ElementKind::SVG: return "svg";
104 case ElementKind::Style: return "style";
105 case ElementKind::Path: return "path";
106 case ElementKind::Text: return "text";
107 case ElementKind::Title: return "title";
108 case ElementKind::Group: return "g";
109 case ElementKind::Line: return "line";
110 case ElementKind::Rect: return "rect";
111 case ElementKind::Circle: return "circle";
112 case ElementKind::Polygon: return "polygon";
113 case ElementKind::Custom: return "";
114 }
115 return "";
116 }
117
118 struct QuadCoord {
119 double x1;
120 double x2;
121 double y1;
122 double y2;
123 };
124
126 using SelectorProperties = std::map<std::string, AttributeMap>;
127 using SVGAttrib = std::map<std::string, std::string>;
129 struct Attrs : SVGAttrib {
130 using SVGAttrib::SVGAttrib;
131 };
132 using Point = std::pair<double, double>;
133 using Margins = QuadCoord;
134 const static Margins DEFAULT_MARGINS = { 10, 10, 10, 10 };
135 const static Margins NO_MARGINS = { 0, 0, 0, 0 };
137 struct AutoscaleOptions {
138 AutoscaleOptions(const Margins& _margins = DEFAULT_MARGINS,
139 bool _autoscale_nested_svgs = true) :
140 margins(_margins),
141 autoscale_nested_svgs(_autoscale_nested_svgs) {}
142
143 Margins margins;
146 };
147
149 enum class RelativeAlignment : unsigned {
150 Left = 1u << 0,
151 Top = 1u << 1,
152 Right = 1u << 2,
153 Bottom = 1u << 3
154 };
155
157 enum class Anchor : unsigned {
158 Start = 1u << 4,
159 Center = 1u << 5,
160 End = 1u << 6
161 };
162
164 enum class Axis {
165 X,
166 Y
167 };
168
170 using Alignment = unsigned;
171
172 inline Alignment operator|(RelativeAlignment relative, Anchor anchor) {
173 return static_cast<Alignment>(relative) | static_cast<Alignment>(anchor);
174 }
175
176 inline Alignment operator|(Anchor anchor, RelativeAlignment relative) {
177 return relative | anchor;
178 }
179
181 class Color {
182 public:
184 static Color rgb(int red, int green, int blue) {
185 return Color(channel(red), channel(green), channel(blue));
186 }
187
189 static Color hex(std::string value) {
190 if (!value.empty() && value[0] == '#') {
191 value.erase(value.begin());
192 }
193 if (value.size() != 3 && value.size() != 6) {
194 throw std::invalid_argument("Hex colors must use 3 or 6 digits");
195 }
196
197 for (auto& ch : value) {
198 if (!std::isxdigit(static_cast<unsigned char>(ch))) {
199 throw std::invalid_argument("Hex colors may only contain hexadecimal digits");
200 }
201 ch = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
202 }
203
204 if (value.size() == 3) {
205 value = std::string{ value[0], value[0],
206 value[1], value[1],
207 value[2], value[2] };
208 }
209
210 return Color(from_hex_pair(value, 0),
211 from_hex_pair(value, 2),
212 from_hex_pair(value, 4));
213 }
214
216 static Color hsl(double hue, double saturation, double lightness) {
217 validate_percentage(saturation, "Saturation");
218 validate_percentage(lightness, "Lightness");
219
220 hue = std::fmod(hue, 360.0);
221 if (hue < 0) {
222 hue += 360.0;
223 }
224
225 const auto s = saturation / 100.0;
226 const auto l = lightness / 100.0;
227 const auto c = (1.0 - std::fabs(2.0 * l - 1.0)) * s;
228 const auto x = c * (1.0 - std::fabs(std::fmod(hue / 60.0, 2.0) - 1.0));
229 const auto m = l - c / 2.0;
230 double red = 0;
231 double green = 0;
232 double blue = 0;
233
234 if (hue < 60) {
235 red = c;
236 green = x;
237 } else if (hue < 120) {
238 red = x;
239 green = c;
240 } else if (hue < 180) {
241 green = c;
242 blue = x;
243 } else if (hue < 240) {
244 green = x;
245 blue = c;
246 } else if (hue < 300) {
247 red = x;
248 blue = c;
249 } else {
250 red = c;
251 blue = x;
252 }
253
254 return Color(channel_from_unit(red + m),
255 channel_from_unit(green + m),
256 channel_from_unit(blue + m));
257 }
258
260 Color mix(const Color& other, double amount) const {
261 validate_unit(amount, "Mix amount");
262 return Color(mix_channel(this->red_, other.red_, amount),
263 mix_channel(this->green_, other.green_, amount),
264 mix_channel(this->blue_, other.blue_, amount));
265 }
266
268 Color tint(double amount) const {
269 return mix(white(), amount);
270 }
271
273 Color shade(double amount) const {
274 return mix(black(), amount);
275 }
276
278 static Color white() {
279 return rgb(255, 255, 255);
280 }
281
283 static Color black() {
284 return rgb(0, 0, 0);
285 }
286
288 operator std::string() const {
289 return serialize();
290 }
291
292 private:
293 Color(uint8_t red, uint8_t green, uint8_t blue) : red_(red), green_(green), blue_(blue) {}
294
295 std::string serialize() const {
296 std::ostringstream ss;
297 ss << '#'
298 << std::hex << std::setfill('0') << std::nouppercase
299 << std::setw(2) << static_cast<int>(red_)
300 << std::setw(2) << static_cast<int>(green_)
301 << std::setw(2) << static_cast<int>(blue_);
302 return ss.str();
303 }
304
305 static uint8_t channel(int value) {
306 if (value < 0 || value > 255) {
307 throw std::invalid_argument("RGB channels must be between 0 and 255");
308 }
309 return static_cast<uint8_t>(value);
310 }
311
312 static uint8_t channel_from_unit(double value) {
313 value = std::max(0.0, std::min(1.0, value));
314 return channel(static_cast<int>(std::round(value * 255.0)));
315 }
316
317 static uint8_t from_hex_pair(const std::string& value, size_t offset) {
318 return static_cast<uint8_t>(std::stoi(value.substr(offset, 2), nullptr, 16));
319 }
320
321 static uint8_t mix_channel(uint8_t from, uint8_t to, double amount) {
322 return channel(static_cast<int>(std::round(from + (to - from) * amount)));
323 }
324
325 static void validate_percentage(double value, const std::string& label) {
326 if (value < 0 || value > 100) {
327 throw std::invalid_argument(label + " must be between 0 and 100");
328 }
329 }
330
331 static void validate_unit(double value, const std::string& label) {
332 if (value < 0 || value > 1) {
333 throw std::invalid_argument(label + " must be between 0 and 1");
334 }
335 }
336
337 uint8_t red_;
338 uint8_t green_;
339 uint8_t blue_;
340 };
341
342#if __cplusplus < 201402L
343 namespace detail {
344 template<typename T, typename... Args>
345 std::unique_ptr<T> make_unique(Args&&... args) {
346 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
347 }
348 }
349#else
350 namespace detail {
351 using std::make_unique;
352 }
353#endif
354
356 namespace detail {
357 template<size_t... I>
358 struct index_sequence {};
359
360 template<size_t N, size_t... I>
361 struct make_index_sequence : make_index_sequence<N - 1, N - 1, I...> {};
362
363 template<size_t... I>
364 struct make_index_sequence<0, I...> {
365 using type = index_sequence<I...>;
366 };
367
368 template<typename T>
369 struct is_attrs : std::is_same<typename std::decay<T>::type, Attrs> {};
370
371 template<typename... Args>
372 struct last_is_attrs : std::false_type {};
373
374 template<typename T>
375 struct last_is_attrs<T> : is_attrs<T> {};
376
377 template<typename T, typename... Rest>
378 struct last_is_attrs<T, Rest...> : last_is_attrs<Rest...> {};
379
380 template<typename T, typename Tuple, size_t... I>
381 std::unique_ptr<T> make_child_with_attrs(Tuple&& tuple, index_sequence<I...>) {
382 const auto attrs = std::get<sizeof...(I)>(tuple);
383 auto child = detail::make_unique<T>(std::get<I>(std::move(tuple))...);
384 for (const auto& attr : attrs) {
385 child->set_attr(attr.first, attr.second);
386 }
387 return child;
388 }
389
390 template<typename T, typename... Args>
391 std::unique_ptr<T> make_child_impl(std::false_type, Args&&... args) {
392 return detail::make_unique<T>(std::forward<Args>(args)...);
393 }
394
395 template<typename T, typename... Args>
396 std::unique_ptr<T> make_child_impl(std::true_type, Args&&... args) {
397 auto tuple = std::forward_as_tuple(std::forward<Args>(args)...);
398 return make_child_with_attrs<T>(
399 std::move(tuple),
400 typename make_index_sequence<sizeof...(Args) - 1>::type{});
401 }
402
403 template<typename T, typename... Args>
404 std::unique_ptr<T> make_child(Args&&... args) {
405 return make_child_impl<T>(last_is_attrs<Args...>{}, std::forward<Args>(args)...);
406 }
407
408 struct AffineTransform {
409 AffineTransform() = default;
410 AffineTransform(double a_, double b_, double c_, double d_, double e_, double f_) :
411 a(a_), b(b_), c(c_), d(d_), e(e_), f(f_) {}
412
413 double a = 1;
414 double b = 0;
415 double c = 0;
416 double d = 1;
417 double e = 0;
418 double f = 0;
419
420 Point apply(Point point) const {
421 return {
422 a * point.first + c * point.second + e,
423 b * point.first + d * point.second + f
424 };
425 }
426 };
427
428 inline AffineTransform multiply(const AffineTransform& left, const AffineTransform& right) {
429 return {
430 left.a * right.a + left.c * right.b,
431 left.b * right.a + left.d * right.b,
432 left.a * right.c + left.c * right.d,
433 left.b * right.c + left.d * right.d,
434 left.a * right.e + left.c * right.f + left.e,
435 left.b * right.e + left.d * right.f + left.f
436 };
437 }
438
439 inline AffineTransform rotate_transform(double degrees, double cx = 0, double cy = 0) {
440 const auto radians = degrees * PI / 180.0;
441 const auto cos_value = std::cos(radians);
442 const auto sin_value = std::sin(radians);
443 return {
444 cos_value,
445 sin_value,
446 -sin_value,
447 cos_value,
448 cx - cos_value * cx + sin_value * cy,
449 cy - sin_value * cx - cos_value * cy
450 };
451 }
452
453 inline AffineTransform translate_transform(double x, double y = 0) {
454 return { 1, 0, 0, 1, x, y };
455 }
456
457 inline double parse_number_or(const std::string& value, double fallback) {
458 if (value.empty()) return fallback;
459 try {
460 return std::stof(value);
461 } catch (const std::invalid_argument&) {
462 return fallback;
463 } catch (const std::out_of_range&) {
464 return fallback;
465 }
466 }
467
468 template<typename T>
469 struct is_numeric_attr_type {
470 static const bool value =
471 std::is_arithmetic<T>::value &&
472 !std::is_same<typename std::remove_cv<T>::type, bool>::value &&
473 !std::is_same<typename std::remove_cv<T>::type, char>::value &&
474 !std::is_same<typename std::remove_cv<T>::type, signed char>::value &&
475 !std::is_same<typename std::remove_cv<T>::type, unsigned char>::value;
476 };
477
478 inline std::vector<double> parse_transform_args(std::string args) {
479 for (auto& ch : args) {
480 if (ch == ',') {
481 ch = ' ';
482 }
483 }
484
485 std::istringstream stream(args);
486 std::vector<double> values;
487 double value;
488 while (stream >> value) {
489 values.push_back(value);
490 }
491 return values;
492 }
493
494 class TextEstimator {
495 public:
496 struct Metrics {
497 double width = 0;
498 double height = 0;
499 double ascent = 0;
500 double descent = 0;
501 };
502
503 TextEstimator(std::string text_, double font_size_, std::string font_weight_) :
504 text(std::move(text_)),
505 font_size(font_size_ > 0 ? font_size_ : 16),
506 font_weight(std::move(font_weight_)) {}
507
509 Metrics estimate() const {
510 const auto bold = is_bold();
511 const double weight_multiplier = bold ? 1.06 : 1.0;
512 const double side_padding = bold ? font_size * 0.05 : font_size * 0.02;
513 const double vertical_padding = bold ? font_size * 0.10 : font_size * 0.06;
514 const double line_height = font_size * (bold ? 1.38 : 1.32);
515 const double ascent = font_size * (bold ? 1.00 : 0.96) + vertical_padding;
516 const double descent = font_size * (bold ? 0.38 : 0.34) + vertical_padding;
517
518 double current = 0;
519 double longest = 0;
520 std::size_t lines = text.empty() ? 0 : 1;
521 bool previous_was_joiner = false;
522 bool regional_pair_open = false;
523 std::size_t index = 0;
524
525 while (index < text.size()) {
526 const auto codepoint = next_codepoint(index);
527 if (codepoint == '\r') {
528 if (index < text.size() && text[index] == '\n') ++index;
529 longest = std::max(longest, current);
530 current = 0;
531 ++lines;
532 previous_was_joiner = false;
533 regional_pair_open = false;
534 continue;
535 }
536 if (codepoint == '\n') {
537 longest = std::max(longest, current);
538 current = 0;
539 ++lines;
540 previous_was_joiner = false;
541 regional_pair_open = false;
542 continue;
543 }
544
545 current += glyph_advance(codepoint, previous_was_joiner, regional_pair_open);
546 previous_was_joiner = codepoint == 0x200d;
547 }
548
549 longest = std::max(longest, current);
550 Metrics metrics;
551 metrics.width = longest == 0 ? 0 : longest * font_size * weight_multiplier + side_padding * 2;
552 metrics.ascent = ascent;
553 metrics.descent = descent;
554 metrics.height = lines == 0 ? 0 : ascent + descent + static_cast<double>(lines - 1) * line_height;
555 return metrics;
556 }
557
558 private:
559 std::string text;
560 double font_size;
561 std::string font_weight;
562
563 bool is_bold() const {
564 auto value = font_weight;
565 for (auto& ch : value) ch = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
566 if (value == "bold" || value == "bolder") return true;
567 return parse_number_or(value, 400) >= 600;
568 }
569
570 uint32_t next_codepoint(std::size_t& index) const {
571 const auto first = static_cast<unsigned char>(text[index++]);
572 if (first < 0x80) return first;
573
574 uint32_t codepoint = 0xfffd;
575 std::size_t continuation_count = 0;
576 if ((first & 0xe0) == 0xc0) {
577 codepoint = first & 0x1f;
578 continuation_count = 1;
579 } else if ((first & 0xf0) == 0xe0) {
580 codepoint = first & 0x0f;
581 continuation_count = 2;
582 } else if ((first & 0xf8) == 0xf0) {
583 codepoint = first & 0x07;
584 continuation_count = 3;
585 } else {
586 return 0xfffd;
587 }
588
589 for (std::size_t i = 0; i < continuation_count; ++i) {
590 if (index >= text.size()) return 0xfffd;
591 const auto next = static_cast<unsigned char>(text[index]);
592 if ((next & 0xc0) != 0x80) return 0xfffd;
593 ++index;
594 codepoint = (codepoint << 6) | (next & 0x3f);
595 }
596
597 if ((continuation_count == 1 && codepoint < 0x80) ||
598 (continuation_count == 2 && codepoint < 0x800) ||
599 (continuation_count == 3 && codepoint < 0x10000) ||
600 codepoint > 0x10ffff ||
601 (codepoint >= 0xd800 && codepoint <= 0xdfff)) {
602 return 0xfffd;
603 }
604 return codepoint;
605 }
606
607 static bool in_range(uint32_t value, uint32_t first, uint32_t last) {
608 return value >= first && value <= last;
609 }
610
611 static bool is_combining_mark(uint32_t codepoint) {
612 return in_range(codepoint, 0x0300, 0x036f) ||
613 in_range(codepoint, 0x0483, 0x0489) ||
614 in_range(codepoint, 0x0591, 0x05bd) ||
615 codepoint == 0x05bf ||
616 in_range(codepoint, 0x05c1, 0x05c2) ||
617 in_range(codepoint, 0x05c4, 0x05c5) ||
618 codepoint == 0x05c7 ||
619 in_range(codepoint, 0x0610, 0x061a) ||
620 in_range(codepoint, 0x064b, 0x065f) ||
621 codepoint == 0x0670 ||
622 in_range(codepoint, 0x06d6, 0x06dc) ||
623 in_range(codepoint, 0x06df, 0x06e4) ||
624 in_range(codepoint, 0x06e7, 0x06e8) ||
625 in_range(codepoint, 0x06ea, 0x06ed) ||
626 in_range(codepoint, 0x1ab0, 0x1aff) ||
627 in_range(codepoint, 0x1dc0, 0x1dff) ||
628 in_range(codepoint, 0x20d0, 0x20ff) ||
629 in_range(codepoint, 0xfe20, 0xfe2f);
630 }
631
632 static bool is_variation_selector(uint32_t codepoint) {
633 return in_range(codepoint, 0xfe00, 0xfe0f) ||
634 in_range(codepoint, 0xe0100, 0xe01ef);
635 }
636
637 static bool is_full_width(uint32_t codepoint) {
638 return in_range(codepoint, 0x1100, 0x115f) ||
639 in_range(codepoint, 0x2329, 0x232a) ||
640 in_range(codepoint, 0x2e80, 0xa4cf) ||
641 in_range(codepoint, 0xac00, 0xd7a3) ||
642 in_range(codepoint, 0xf900, 0xfaff) ||
643 in_range(codepoint, 0xfe10, 0xfe19) ||
644 in_range(codepoint, 0xfe30, 0xfe6f) ||
645 in_range(codepoint, 0xff00, 0xff60) ||
646 in_range(codepoint, 0xffe0, 0xffe6);
647 }
648
649 static bool is_emoji_or_symbol(uint32_t codepoint) {
650 return in_range(codepoint, 0x1f000, 0x1faff) ||
651 in_range(codepoint, 0x2600, 0x27bf) ||
652 in_range(codepoint, 0x2190, 0x21ff) ||
653 in_range(codepoint, 0x2300, 0x23ff);
654 }
655
656 static bool is_regional_indicator(uint32_t codepoint) {
657 return in_range(codepoint, 0x1f1e6, 0x1f1ff);
658 }
659
660 static bool is_latin_letter(uint32_t codepoint) {
661 return in_range(codepoint, 'A', 'Z') ||
662 in_range(codepoint, 'a', 'z') ||
663 in_range(codepoint, 0x00c0, 0x024f);
664 }
665
666 static double ascii_advance(uint32_t codepoint) {
667 switch (codepoint) {
668 case ' ':
669 case '\t':
670 case '.':
671 case ',':
672 case ':':
673 case ';':
674 case '\'':
675 case '"':
676 case '`':
677 case '!':
678 case '|':
679 return 0.34;
680 case 'i':
681 case 'j':
682 case 'l':
683 case 'I':
684 case '[':
685 case ']':
686 case '(':
687 case ')':
688 case '{':
689 case '}':
690 return 0.40;
691 case 'm':
692 case 'w':
693 case 'M':
694 case 'W':
695 case '@':
696 case '%':
697 case '&':
698 return 0.92;
699 case '-':
700 case '_':
701 case '/':
702 case '\\':
703 return 0.52;
704 default:
705 break;
706 }
707
708 if (in_range(codepoint, '0', '9')) return 0.64;
709 if (in_range(codepoint, 'A', 'Z')) return 0.72;
710 if (in_range(codepoint, 'a', 'z')) return 0.62;
711 return 0.58;
712 }
713
714 static double glyph_advance(uint32_t codepoint,
715 bool previous_was_joiner,
716 bool& regional_pair_open) {
717 if (is_combining_mark(codepoint) ||
718 is_variation_selector(codepoint) ||
719 codepoint == 0x200d ||
720 in_range(codepoint, 0x1f3fb, 0x1f3ff)) {
721 return 0;
722 }
723
724 if (previous_was_joiner) return 0;
725
726 if (is_regional_indicator(codepoint)) {
727 regional_pair_open = !regional_pair_open;
728 return regional_pair_open ? 1.10 : 0;
729 }
730 regional_pair_open = false;
731
732 if (codepoint < 0x80) return ascii_advance(codepoint);
733 if (is_full_width(codepoint)) return 1.05;
734 if (is_emoji_or_symbol(codepoint)) return 1.10;
735 if (is_latin_letter(codepoint)) return 0.66;
736 return 0.85;
737 }
738 };
739
740 inline AffineTransform parse_supported_transform(const std::string& transform) {
741 AffineTransform current;
742 size_t pos = 0;
743 while (pos < transform.size()) {
744 while (pos < transform.size() && std::isspace(static_cast<unsigned char>(transform[pos]))) {
745 ++pos;
746 }
747 const auto name_start = pos;
748 while (pos < transform.size() && std::isalpha(static_cast<unsigned char>(transform[pos]))) {
749 ++pos;
750 }
751 if (name_start == pos) {
752 break;
753 }
754
755 const auto name = transform.substr(name_start, pos - name_start);
756 while (pos < transform.size() && std::isspace(static_cast<unsigned char>(transform[pos]))) {
757 ++pos;
758 }
759 if (pos >= transform.size() || transform[pos] != '(') {
760 break;
761 }
762 const auto args_start = ++pos;
763 const auto args_end = transform.find(')', args_start);
764 if (args_end == std::string::npos) {
765 break;
766 }
767 pos = args_end + 1;
768
769 const auto args = parse_transform_args(transform.substr(args_start, args_end - args_start));
770 if (name == "rotate" && (args.size() == 1 || args.size() == 3)) {
771 current = multiply(
772 current,
773 args.size() == 1 ? rotate_transform(args[0])
774 : rotate_transform(args[0], args[1], args[2]));
775 } else if (name == "translate" && (args.size() == 1 || args.size() == 2)) {
776 current = multiply(
777 current,
778 args.size() == 1 ? translate_transform(args[0])
779 : translate_transform(args[0], args[1]));
780 }
781 }
782 return current;
783 }
784 }
786
787 inline std::string to_string(const double& value);
788 inline std::string to_string(const Point& point);
790 inline std::string to_string(const Color& color);
791 inline std::string to_string(const std::map<std::string, AttributeMap>& css, const size_t indent_level=0);
793 inline std::string escape_xml(const std::string& text);
794
795 std::vector<Point> bounding_polygon(const std::vector<Shape*>& shapes);
796 SVG frame_animate(std::vector<SVG>& frames, const double fps);
797 SVG merge(SVG& left, SVG& right, const Margins& margins = DEFAULT_MARGINS);
798 SVG merge(std::vector<SVG>& frames, const double width, const int max_frame_width);
799
803 class ClassList {
804 public:
805 ClassList() = default;
806 explicit ClassList(std::string& value) : mutable_value_(&value), value_(&value) {}
807 explicit ClassList(const std::string& value) : value_(&value) {}
808
810 bool contains(const std::string& token) const {
811 validate_token(token);
812 const auto values = tokens();
813 return std::find(values.begin(), values.end(), token) != values.end();
814 }
815
817 ClassList& add(const std::string& token) {
818 validate_token(token);
819 auto values = tokens();
820 if (std::find(values.begin(), values.end(), token) == values.end()) {
821 values.push_back(token);
822 write(values);
823 }
824 return *this;
825 }
826
828 ClassList& remove(const std::string& token) {
829 validate_token(token);
830 auto values = tokens();
831 const auto original_size = values.size();
832 values.erase(std::remove(values.begin(), values.end(), token), values.end());
833 if (values.size() != original_size) {
834 write(values);
835 }
836 return *this;
837 }
838
840 bool toggle(const std::string& token) {
841 if (contains(token)) {
842 remove(token);
843 return false;
844 }
845
846 add(token);
847 return true;
848 }
849
851 ClassList& set(const std::string& class_names) {
852 write(parse(class_names));
853 return *this;
854 }
855
857 ClassList& clear() {
858 write({});
859 return *this;
860 }
861
863 std::string str() const {
864 return join(tokens());
865 }
866
868 std::vector<std::string> tokens() const {
869 return parse(value());
870 }
871
872 private:
873 static bool is_space(char ch) {
874 return std::isspace(static_cast<unsigned char>(ch)) != 0;
875 }
876
877 static void validate_token(const std::string& token) {
878 if (token.empty()) {
879 throw std::invalid_argument("class token cannot be empty");
880 }
881 if (std::find_if(token.begin(), token.end(), is_space) != token.end()) {
882 throw std::invalid_argument("class token cannot contain whitespace");
883 }
884 }
885
886 static std::vector<std::string> parse(const std::string& class_names) {
887 std::vector<std::string> result;
888 std::string token;
889 for (const auto ch : class_names) {
890 if (is_space(ch)) {
891 if (!token.empty()) {
892 if (std::find(result.begin(), result.end(), token) == result.end()) {
893 result.push_back(token);
894 }
895 token.clear();
896 }
897 continue;
898 }
899 token.push_back(ch);
900 }
901 if (!token.empty() && std::find(result.begin(), result.end(), token) == result.end()) {
902 result.push_back(token);
903 }
904 return result;
905 }
906
907 static std::string join(const std::vector<std::string>& values) {
908 std::string result;
909 for (std::size_t i = 0; i < values.size(); ++i) {
910 if (i > 0) {
911 result += ' ';
912 }
913 result += values[i];
914 }
915 return result;
916 }
917
918 const std::string& value() const {
919 static const std::string empty;
920 return value_ ? *value_ : empty;
921 }
922
923 void write(const std::vector<std::string>& values) {
924 if (!mutable_value_) {
925 throw std::logic_error("cannot mutate a const class list");
926 }
927 *mutable_value_ = join(values);
928 value_ = mutable_value_;
929 }
930
931 std::string* mutable_value_ = nullptr;
932 const std::string* value_ = nullptr;
933 };
934
938 class TransformList {
939 public:
940 TransformList() = default;
941 explicit TransformList(std::string& value, const Element* owner = nullptr) :
942 mutable_value_(&value), value_(&value), owner_(owner) {}
943 explicit TransformList(const std::string& value, const Element* owner = nullptr) :
944 value_(&value), owner_(owner) {}
945
947 TransformList& append(const std::string& transform) {
948 validate_appendable();
949 if (transform.empty()) {
950 throw std::invalid_argument("transform cannot be empty");
951 }
952
953 if (str().empty() || str() == "none") {
954 write(transform);
955 } else {
956 write(str() + " " + transform);
957 }
958 return *this;
959 }
960
962 TransformList& set(const std::string& transform) {
963 write(transform);
964 return *this;
965 }
966
968 TransformList& clear() {
969 write("");
970 return *this;
971 }
972
973 TransformList& matrix(double a, double b, double c, double d, double e, double f) {
974 std::stringstream ss;
975 ss << "matrix(" << to_string(a) << " " << to_string(b) << " " << to_string(c)
976 << " " << to_string(d) << " " << to_string(e) << " " << to_string(f) << ")";
977 return append(ss.str());
978 }
979
980 TransformList& translate(double x) {
981 return append("translate(" + to_string(x) + ")");
982 }
983
984 TransformList& translate(double x, double y) {
985 return append("translate(" + to_string(x) + " " + to_string(y) + ")");
986 }
987
988 TransformList& scale(double factor) {
989 return append("scale(" + to_string(factor) + ")");
990 }
991
992 TransformList& scale(double x, double y) {
993 return append("scale(" + to_string(x) + " " + to_string(y) + ")");
994 }
995
996 TransformList& rotate(double degrees) {
997 return append("rotate(" + to_string(degrees) + ")");
998 }
999
1000 TransformList& rotate(double degrees, double cx, double cy) {
1001 return append("rotate(" + to_string(degrees) + " " + to_string(cx) + " " +
1002 to_string(cy) + ")");
1003 }
1004
1006 TransformList& rotate_about_bbox(double degrees, Anchor x_anchor, Anchor y_anchor);
1007
1008 TransformList& skew_x(double degrees) {
1009 return append("skewX(" + to_string(degrees) + ")");
1010 }
1011
1012 TransformList& skew_y(double degrees) {
1013 return append("skewY(" + to_string(degrees) + ")");
1014 }
1015
1017 std::string str() const {
1018 return value();
1019 }
1020
1021 private:
1022 static bool is_keyword(const std::string& transform) {
1023 return transform == "inherit" || transform == "initial" || transform == "revert" ||
1024 transform == "revert-layer" || transform == "unset";
1025 }
1026
1027 const std::string& value() const {
1028 static const std::string empty;
1029 return value_ ? *value_ : empty;
1030 }
1031
1032 void validate_appendable() const {
1033 if (is_keyword(value())) {
1034 throw std::logic_error("cannot append transform functions to a transform keyword");
1035 }
1036 }
1037
1038 void write(const std::string& value) {
1039 if (!mutable_value_) {
1040 throw std::logic_error("cannot mutate a const transform list");
1041 }
1042 *mutable_value_ = value;
1043 value_ = mutable_value_;
1044 }
1045
1046 std::string* mutable_value_ = nullptr;
1047 const std::string* value_ = nullptr;
1048 const Element* owner_ = nullptr;
1049 };
1050
1054 namespace util {
1055 enum Orientation {
1056 COLINEAR, CLOCKWISE, COUNTERCLOCKWISE
1057 };
1058
1059 inline std::vector<Point> polar_points(int n, int a, int b, double radius);
1060
1061 template<typename T>
1062 inline T min_or_not_nan(T first, T second) {
1066 if (isnan(first) && isnan(second))
1067 return NAN;
1068 else if (isnan(first) || isnan(second))
1069 return isnan(first) ? second : first;
1070 else
1071 return std::min(first, second);
1072 }
1073
1074 template<typename T>
1075 inline T max_or_not_nan(T first, T second) {
1079 if (isnan(first) && isnan(second))
1080 return NAN;
1081 else if (isnan(first) || isnan(second))
1082 return isnan(first) ? second : first;
1083 else
1084 return std::max(first, second);
1085 }
1086
1087 inline Orientation orientation(Point& p1, Point& p2, Point& p3) {
1088 double value = ((p2.second - p1.second) * (p3.first - p2.first) -
1089 (p2.first - p1.first) * (p3.second - p2.second));
1090
1091 if (value == 0) return COLINEAR;
1092 else if (value > 0) return CLOCKWISE;
1093 else return COUNTERCLOCKWISE;
1094 }
1095
1096 inline std::vector<Point> convex_hull(std::vector<Point>& points) {
1102
1103 if (points.size() < 3) return {}; // Need at least three points
1104 std::vector<Point> hull;
1105
1106 // Find leftmost point (ties don't matter)
1107 int left = 0;
1108 for (size_t i = 0; i < points.size(); i++)
1109 if (points[i].first < points[left].first) left = (int)i;
1110
1111 // While we don't reach leftmost point
1112 int current = left, next;
1113 do {
1114 // Add to convex hull
1115 hull.push_back(points[current]);
1116
1117 // Keep moving counterclockwise
1118 next = (current + 1) % points.size();
1119 for (size_t i = 0; i < points.size(); i++) {
1120 // We've found a more counterclockwise point --> update next
1121 if (orientation(points[current], points[next], points[i]) == COUNTERCLOCKWISE)
1122 next = (int)i;
1123 }
1124
1125 current = next;
1126 } while (current != left);
1127
1128 return hull;
1129 }
1130
1131 inline std::vector<Point> polar_points(int n, int a, int b, double radius) {
1138 std::vector<Point> ret;
1139 for (double degree = 0; degree < 360; degree += 360/n) {
1140 ret.push_back(Point(
1141 a + radius * cos(degree * (PI/180)), // 1 degree = pi/180 radians
1142 b + radius * sin(degree * (PI/180))
1143 ));
1144 }
1145
1146 return ret;
1147 }
1148 }
1149
1150 inline std::string to_string(const double& value) {
1152 std::stringstream ss;
1153 ss << std::fixed << std::setprecision(1);
1154 ss << value;
1155 return ss.str();
1156 }
1157
1158 inline std::string to_string(const Point& point) {
1160 return to_string(point.first) + "," + to_string(point.second);
1161 }
1162
1163 inline std::string to_string(const Color& color) {
1165 return static_cast<std::string>(color);
1166 }
1167
1168 namespace detail {
1169 inline void append_escaped_xml(std::string& out, const std::string& text) {
1170 size_t start = 0;
1171 for (size_t i = 0; i < text.size(); ++i) {
1172 const char* entity;
1173 switch (text[i]) {
1174 case '&': entity = "&amp;"; break;
1175 case '<': entity = "&lt;"; break;
1176 case '>': entity = "&gt;"; break;
1177 case '"': entity = "&quot;"; break;
1178 case '\'': entity = "&apos;"; break;
1179 default: continue;
1180 }
1181 out.append(text, start, i - start);
1182 out += entity;
1183 start = i + 1;
1184 }
1185 out.append(text, start, text.size() - start);
1186 }
1187 }
1188
1189 inline std::string escape_xml(const std::string& text) {
1190 std::string out;
1191 detail::append_escaped_xml(out, text);
1192 return out;
1193 }
1194
1198 class AttributeMap {
1199 public:
1200 struct AttrSetter {
1201 AttrSetter(SVGAttrib::mapped_type& _attr,
1202 bool _normalize_class = false,
1203 std::function<void(const std::string&)> _on_update = {}) :
1204 attr_(_attr), normalize_class_(_normalize_class), on_update_(_on_update) {};
1205
1207 AttrSetter& operator<<(const Color& value) {
1208 attr_ += static_cast<std::string>(value);
1209 normalize();
1210 notify();
1211 return *this;
1212 }
1213
1214 template<typename T>
1215 AttrSetter& operator<<(T value) {
1216 attr_ += std::to_string(value);
1217 normalize();
1218 notify();
1219 return *this;
1220 }
1221
1222 private:
1223 void normalize() {
1224 if (normalize_class_) {
1225 ClassList(attr_).set(attr_);
1226 }
1227 }
1228
1229 void notify() {
1230 if (on_update_) {
1231 on_update_(attr_);
1232 }
1233 }
1234
1235 SVGAttrib::mapped_type& attr_;
1236 bool normalize_class_ = false;
1237 std::function<void(const std::string&)> on_update_;
1238 };
1239
1240 AttributeMap() = default;
1241 virtual ~AttributeMap() = default;
1242 AttributeMap(SVGAttrib _attr) : attr_(std::move(_attr)) {};
1243
1244 const SVGAttrib& attrs() const {
1245 return this->attr_;
1246 }
1247
1248 bool has_attr(const std::string& key) const {
1249 return this->attr_.find(key) != this->attr_.end();
1250 }
1251
1252 std::string get_attr(const std::string& key, const std::string& fallback = "") const {
1253 const auto found = this->attr_.find(key);
1254 return found == this->attr_.end() ? fallback : found->second;
1255 }
1256
1258 template<typename T>
1259 typename std::enable_if<detail::is_numeric_attr_type<T>::value, T>::type
1260 get_attr(const std::string& key, T fallback) const {
1261 const auto found = this->attr_.find(key);
1262 if (found == this->attr_.end()) return fallback;
1263 return static_cast<T>(detail::parse_number_or(found->second, static_cast<double>(fallback)));
1264 }
1265
1266 template<typename T>
1267 AttributeMap& set_attr(const std::string key, T value) {
1268 this->set_attr_value(key, std::to_string(value));
1269 return *this;
1270 }
1271
1273 AttributeMap& set_attr(const std::string key, const Color& value);
1274
1276 AttributeMap& set_attrs(std::initializer_list<std::pair<std::string, std::string>> values) {
1277 for (const auto& pair : values) {
1278 this->set_attr_value(pair.first, pair.second);
1279 }
1280
1281 return *this;
1282 }
1283
1285 AttributeMap& set_attrs(const SVGAttrib& values) {
1286 for (const auto& pair : values) {
1287 this->set_attr_value(pair.first, pair.second);
1288 }
1289
1290 return *this;
1291 }
1292
1293 AttrSetter set_attr(const std::string key) {
1294 return this->make_attr_setter(key);
1295 };
1296
1297 ClassList class_list() {
1298 return ClassList(this->attr_["class"]);
1299 }
1300
1301 ClassList class_list() const {
1302 const auto found = this->attr_.find("class");
1303 return found == this->attr_.end() ? ClassList() : ClassList(found->second);
1304 }
1305
1306 TransformList transform_list() {
1307 return TransformList(this->attr_["transform"]);
1308 }
1309
1310 TransformList transform_list() const {
1311 const auto found = this->attr_.find("transform");
1312 return found == this->attr_.end() ? TransformList() : TransformList(found->second);
1313 }
1314
1315 TransformList transform() {
1316 return transform_list();
1317 }
1318
1319 TransformList transform() const {
1320 return transform_list();
1321 }
1322
1323 protected:
1324 virtual void set_attr_value(const std::string& key, const std::string& value) {
1325 if (key == "class") {
1326 ClassList(this->attr_[key]).set(value);
1327 return;
1328 }
1329 this->attr_[key] = value;
1330 }
1331
1332 virtual AttrSetter make_attr_setter(const std::string& key) {
1333 if (this->attr_.find(key) == this->attr_.end()) this->attr_[key] = "";
1334 return AttrSetter(this->attr_.at(key), key == "class");
1335 }
1336
1337 SVGAttrib& mutable_attrs() {
1338 return this->attr_;
1339 }
1340
1341 private:
1342 SVGAttrib attr_;
1343 };
1344
1345 template<>
1347 attr_ += value;
1348 normalize();
1349 notify();
1350 return *this;
1351 }
1352
1353 template<>
1354 inline AttributeMap::AttrSetter& AttributeMap::AttrSetter::operator<<(const std::string value) {
1355 attr_ += value;
1356 normalize();
1357 notify();
1358 return *this;
1359 }
1360
1361 template<>
1362 inline AttributeMap& AttributeMap::set_attr(const std::string key, const double value) {
1364 this->set_attr_value(key, to_string(value));
1365 return *this;
1366 }
1367
1368 inline AttributeMap& AttributeMap::set_attr(const std::string key, const Color& value) {
1369 this->set_attr_value(key, static_cast<std::string>(value));
1370 return *this;
1371 }
1372
1373 template<>
1374 inline AttributeMap& AttributeMap::set_attr(const std::string key, const char * value) {
1376 this->set_attr_value(key, value);
1377 return *this;
1378 }
1379
1380 template<>
1381 inline AttributeMap& AttributeMap::set_attr(const std::string key, const std::string value) {
1383 this->set_attr_value(key, value);
1384 return *this;
1385 }
1386
1388 namespace detail {
1390 template<typename T>
1391 class TypedNames {
1392 static_assert(std::is_enum<T>::value, "Typed CSS keys must be an enum type.");
1393
1394 public:
1396 std::string name(T key) const {
1397 const auto found = this->names_.find(key);
1398 if (found == this->names_.end()) {
1399 throw std::invalid_argument("Unknown typed CSS key");
1400 }
1401 return found->second;
1402 }
1403
1404 protected:
1406 void add_name(T key, const std::string& normalized_name, const std::string& duplicate_label) {
1407 if (this->names_.find(key) != this->names_.end()) {
1408 throw std::invalid_argument("Duplicate typed CSS key");
1409 }
1410 if (this->used_names_.find(normalized_name) != this->used_names_.end()) {
1411 throw std::invalid_argument("Duplicate " + duplicate_label + ": " + normalized_name);
1412 }
1413
1414 this->names_[key] = normalized_name;
1415 this->used_names_.insert(normalized_name);
1416 }
1417
1418 private:
1420 std::map<T, std::string> names_;
1422 std::set<std::string> used_names_;
1423 };
1424 }
1426
1428 template<typename T>
1433 std::string css_name;
1435 bool has_value = false;
1437 std::string value;
1438
1440 VariableSpec(T _key, std::string _css_name) :
1441 key(_key), css_name(std::move(_css_name)) {}
1442
1444 VariableSpec(T _key, std::string _css_name, std::string _value) :
1445 key(_key),
1446 css_name(std::move(_css_name)),
1447 has_value(true),
1448 value(std::move(_value)) {}
1449 };
1450
1452 template<typename T>
1453 struct ClassSpec {
1457 std::string css_class;
1458
1460 ClassSpec(T _key, std::string _css_class) :
1461 key(_key), css_class(std::move(_css_class)) {}
1462 };
1463
1465 template<typename T>
1466 class Variables : public detail::TypedNames<T> {
1467 public:
1469 Variables(AttributeMap& target, std::initializer_list<VariableSpec<T>> specs) :
1470 target_(&target) {
1471 std::vector<std::pair<T, std::string>> initial_values;
1472
1473 for (const auto& spec : specs) {
1474 const auto normalized_name = normalize_name(spec.css_name);
1475 this->add_name(spec.key, normalized_name, "CSS variable name");
1476 if (spec.has_value) {
1477 initial_values.push_back({ spec.key, spec.value });
1478 }
1479 }
1480
1481 for (const auto& initial : initial_values) {
1482 this->set(initial.first, initial.second);
1483 }
1484 }
1485
1487 std::string var(T key) const {
1488 return "var(" + this->name(key) + ")";
1489 }
1490
1492 Variables& set(T key, const std::string& value) {
1493 this->target_->set_attr(this->name(key), value);
1494 return *this;
1495 }
1496
1498 Variables& set(T key, const char* value) {
1499 return this->set(key, std::string(value));
1500 }
1501
1503 template<typename... Keys>
1504 std::string format(const std::string& pattern, Keys... keys) const {
1505 std::vector<std::string> args = { this->var(keys)... };
1506 std::vector<bool> used(args.size(), false);
1507 std::string out;
1508
1509 for (size_t i = 0; i < pattern.size(); ++i) {
1510 if (pattern[i] == '{') {
1511 if (i + 1 < pattern.size() && pattern[i + 1] == '{') {
1512 out.push_back('{');
1513 ++i;
1514 continue;
1515 }
1516
1517 const auto start = i + 1;
1518 auto pos = start;
1519 size_t index = 0;
1520 while (pos < pattern.size() && std::isdigit(static_cast<unsigned char>(pattern[pos]))) {
1521 index = index * 10 + static_cast<size_t>(pattern[pos] - '0');
1522 ++pos;
1523 }
1524 if (pos == start || pos >= pattern.size() || pattern[pos] != '}') {
1525 throw std::invalid_argument("Malformed CSS variable format placeholder");
1526 }
1527 if (index >= args.size()) {
1528 throw std::invalid_argument("CSS variable format placeholder index out of range");
1529 }
1530
1531 out += args[index];
1532 used[index] = true;
1533 i = pos;
1534 } else if (pattern[i] == '}') {
1535 if (i + 1 < pattern.size() && pattern[i + 1] == '}') {
1536 out.push_back('}');
1537 ++i;
1538 continue;
1539 }
1540 throw std::invalid_argument("Unmatched CSS variable format brace");
1541 } else {
1542 out.push_back(pattern[i]);
1543 }
1544 }
1545
1546 for (const auto was_used : used) {
1547 if (!was_used) {
1548 throw std::invalid_argument("Unused CSS variable format argument");
1549 }
1550 }
1551
1552 return out;
1553 }
1554
1555 private:
1557 static std::string normalize_name(const std::string& css_name) {
1558 if (css_name.empty()) {
1559 throw std::invalid_argument("CSS variable name cannot be empty");
1560 }
1561 if (css_name.size() >= 2 && css_name[0] == '-' && css_name[1] == '-') {
1562 return css_name;
1563 }
1564 return "--" + css_name;
1565 }
1566
1568 AttributeMap* target_;
1569 };
1570
1572 template<typename T>
1573 class Classes : public detail::TypedNames<T> {
1574 public:
1576 Classes(std::initializer_list<ClassSpec<T>> specs) {
1577 for (const auto& spec : specs) {
1578 this->add_name(spec.key, normalize_name(spec.css_class), "CSS class name");
1579 }
1580 }
1581
1583 template<typename... Keys>
1584 std::string selector(Keys... keys) const {
1585 const auto names = this->names(keys...);
1586 std::string out;
1587 for (const auto& name : names) {
1588 out += "." + name;
1589 }
1590 return out;
1591 }
1592
1594 template<typename... Keys>
1595 std::string classes(Keys... keys) const {
1596 const auto names = this->names(keys...);
1597 std::string out;
1598 for (const auto& name : names) {
1599 if (!out.empty()) out += " ";
1600 out += name;
1601 }
1602 return out;
1603 }
1604
1605 private:
1606 static std::string normalize_name(std::string css_class) {
1607 if (!css_class.empty() && css_class[0] == '.') {
1608 css_class.erase(0, 1);
1609 }
1610 if (css_class.empty()) {
1611 throw std::invalid_argument("CSS class name cannot be empty");
1612 }
1613 for (const auto ch : css_class) {
1614 if (std::isspace(static_cast<unsigned char>(ch))) {
1615 throw std::invalid_argument("CSS class name cannot contain whitespace");
1616 }
1617 }
1618 return css_class;
1619 }
1620
1621 template<typename... Keys>
1622 std::vector<std::string> names(Keys... keys) const {
1623 return std::vector<std::string>{ this->name(keys)... };
1624 }
1625 };
1626
1630 class Element: public AttributeMap {
1631 public:
1635 class BoundingBox : public QuadCoord {
1636 public:
1637 using QuadCoord::QuadCoord;
1638 BoundingBox() = default;
1639 BoundingBox(double a, double b, double c, double d) : QuadCoord({ a, b, c, d }) {};
1640
1641 BoundingBox operator+ (const BoundingBox& other) const {
1643 using namespace util;
1644 BoundingBox new_box;
1645 new_box.x1 = min_or_not_nan(this->x1, other.x1);
1646 new_box.x2 = max_or_not_nan(this->x2, other.x2);
1647 new_box.y1 = min_or_not_nan(this->y1, other.y1);
1648 new_box.y2 = max_or_not_nan(this->y2, other.y2);
1649 return new_box;
1650 }
1651 };
1652 using ChildList = std::vector<Element*>;
1653 using ConstChildList = std::vector<const Element*>;
1654 using ChildMap = std::map<std::string, ChildList>;
1655 using ConstChildMap = std::map<std::string, ConstChildList>;
1656 class DepthFirstIterator;
1657 class ConstDepthFirstIterator;
1658 class DepthFirstRange;
1659 class ConstDepthFirstRange;
1660 struct TraversalOptions {
1661 TraversalOptions(bool _descend_into_nested_svgs = true) :
1662 descend_into_nested_svgs(_descend_into_nested_svgs) {}
1663
1666 };
1667
1668 Element() = default;
1669 virtual ~Element() = default;
1671 Element(const Element& other);
1672 Element(Element&& other) noexcept :
1673 AttributeMap(std::move(other)),
1674 children(std::move(other.children)),
1675 parent_(nullptr),
1676 owner_(nullptr),
1677 indexed_id_(),
1678 has_layout_bbox_(other.has_layout_bbox_),
1679 layout_bbox_(other.layout_bbox_),
1680 layout_bbox_padding_(other.layout_bbox_padding_) {
1681 other.has_layout_bbox_ = false;
1682 reparent_children();
1683 }
1684 Element& operator=(const Element&) = delete; // No copy assignment
1685 Element& operator=(Element&& other) noexcept {
1686 if (this != &other) {
1687 AttributeMap::operator=(std::move(other));
1688 children = std::move(other.children);
1689 parent_ = nullptr;
1690 owner_ = nullptr;
1691 indexed_id_.clear();
1692 has_layout_bbox_ = other.has_layout_bbox_;
1693 layout_bbox_ = other.layout_bbox_;
1694 layout_bbox_padding_ = other.layout_bbox_padding_;
1695 other.has_layout_bbox_ = false;
1696 reparent_children();
1697 }
1698 return *this;
1699 }
1700
1701 Element(const char* id) : AttributeMap(
1702 SVGAttrib({ { "id", id } })) {};
1703 using AttributeMap::AttributeMap;
1704
1705 // Implicit string conversion
1706 operator std::string() const { return this->svg_to_string(0); };
1707
1711 std::unique_ptr<Element> clone_element() const;
1712
1713 template<typename T, typename... Args>
1714 T* add_child(Args&&... args) {
1716 SVG_TYPE_CHECK;
1717 auto child = detail::make_child<T>(std::forward<Args>(args)...);
1718 return this->insert_new_child(std::move(child), this->children.end());
1719 }
1720
1721 template<typename T>
1722 Element& operator<<(T&& node) {
1724 SVG_TYPE_CHECK;
1725 auto child = detail::make_unique<T>(std::move(node));
1726 this->insert_new_child(std::move(child), this->children.end());
1727 return *this;
1728 }
1729
1730 template<typename T>
1731 std::vector<T*> get_children() {
1733 SVG_TYPE_CHECK;
1734 std::vector<T*> ret;
1735 auto child_elems = this->get_children_helper();
1736
1737 for (auto& child: child_elems)
1738 if (child->kind() == T::static_kind) ret.push_back(static_cast<T*>(child));
1739
1740 return ret;
1741 }
1742
1743 template<typename T>
1744 std::vector<const T*> get_children() const {
1746 SVG_TYPE_CHECK;
1747 std::vector<const T*> ret;
1748 auto child_elems = this->get_children_helper();
1749
1750 for (auto& child: child_elems)
1751 if (child->kind() == T::static_kind) ret.push_back(static_cast<const T*>(child));
1752
1753 return ret;
1754 }
1755
1756 template<typename T>
1757 std::vector<T*> get_immediate_children() {
1759 SVG_TYPE_CHECK;
1760 std::vector<T*> ret;
1761 for (auto& child : this->children) {
1762 if (child->kind() == T::static_kind) ret.push_back(static_cast<T*>(child.get()));
1763 }
1764
1765 return ret;
1766 }
1767
1768 template<typename T>
1769 std::vector<const T*> get_immediate_children() const {
1771 SVG_TYPE_CHECK;
1772 std::vector<const T*> ret;
1773 for (auto& child : this->children) {
1774 if (child->kind() == T::static_kind) ret.push_back(static_cast<const T*>(child.get()));
1775 }
1776
1777 return ret;
1778 }
1779
1780 Element* get_element_by_id(const std::string& id);
1781 const Element* get_element_by_id(const std::string& id) const;
1782 std::vector<Element*> get_elements_by_class(const std::string& clsname);
1783 std::vector<const Element*> get_elements_by_class(const std::string& clsname) const;
1784 const Element* parent() const { return parent_; }
1786 virtual ElementKind kind() const { return ElementKind::Custom; }
1787 Element& id(const std::string& value);
1788 std::string id() const;
1789 void autoscale(const Margins& margins=DEFAULT_MARGINS);
1790 void autoscale(const double margin);
1792 void autoscale(const AutoscaleOptions& options);
1794 void responsive_autoscale(const Margins& margins=DEFAULT_MARGINS);
1796 void responsive_autoscale(const double margin);
1798 void responsive_autoscale(const AutoscaleOptions& options);
1800 Element& layout_bbox(const BoundingBox& bbox);
1802 Element& bbox_padding(const Margins& padding);
1804 Element& bbox_padding(double padding);
1806 Element& clear_layout_bbox();
1808 bool has_layout_bbox() const { return has_layout_bbox_; }
1810 BoundingBox layout_bbox() const;
1812 Element& snap_to(const Element& target,
1813 RelativeAlignment relative,
1814 Point offset = Point(0, 0));
1816 Element& snap_to(const Element& target,
1817 Alignment alignment,
1818 Point offset = Point(0, 0));
1820 Element& align_to(const Element& target,
1821 Axis axis,
1822 Point offset = Point(0, 0));
1824 Element& align_to(const Element& target,
1825 Axis axis,
1826 Anchor anchor,
1827 Point offset = Point(0, 0));
1828 TransformList transform_list() {
1829 return TransformList(this->mutable_attrs()["transform"], this);
1830 }
1831 TransformList transform_list() const {
1832 const auto& attributes = this->attrs();
1833 const auto found = attributes.find("transform");
1834 return found == attributes.end() ? TransformList() : TransformList(found->second, this);
1835 }
1836 TransformList transform() {
1837 return transform_list();
1838 }
1839 TransformList transform() const {
1840 return transform_list();
1841 }
1842 virtual BoundingBox get_bbox() const;
1843 ChildMap get_children();
1844 ConstChildMap get_children() const;
1846 DepthFirstIterator begin();
1848 ConstDepthFirstIterator begin() const;
1849 DepthFirstIterator end();
1850 ConstDepthFirstIterator end() const;
1852 DepthFirstRange depth_first();
1854 DepthFirstRange depth_first(TraversalOptions options);
1856 ConstDepthFirstRange depth_first() const;
1858 ConstDepthFirstRange depth_first(TraversalOptions options) const;
1860 DepthFirstRange descendants();
1862 DepthFirstRange descendants(TraversalOptions options);
1864 ConstDepthFirstRange descendants() const;
1866 ConstDepthFirstRange descendants(TraversalOptions options) const;
1867
1868 protected:
1869 std::vector<std::unique_ptr<Element>> children;
1870 using ChildIterator = std::vector<std::unique_ptr<Element>>::iterator;
1871 std::vector<Element*> get_children_helper();
1872 std::vector<const Element*> get_children_helper() const;
1873 BoundingBox get_autoscale_bbox() const;
1874 BoundingBox measured_layout_bbox() const;
1875 BoundingBox include_stroke_width(const BoundingBox& bbox) const;
1876 void autoscale_nested_svgs(const AutoscaleOptions& options, bool responsive);
1877 static detail::AffineTransform transform_for(const Element* element,
1878 const detail::AffineTransform& parent_transform);
1879 void get_bbox(Element::BoundingBox&, bool visible_only = true) const;
1880 void set_viewbox_from_bbox(const BoundingBox& bbox, const Margins& margins);
1881 virtual std::string svg_to_string(const size_t indent_level) const;
1882 virtual std::string tag() { return tag_name(this->kind()); }
1884 virtual std::string tag() const { return const_cast<Element*>(this)->tag(); }
1885 virtual std::unique_ptr<Element> clone_element_impl() const;
1886
1887 template<typename T>
1888 std::unique_ptr<T> clone_as() const {
1889 static_assert(std::is_copy_constructible<T>::value,
1890 "Cloneable SVG element subclasses must be copy constructible.");
1891 auto copy = detail::make_unique<T>(static_cast<const T&>(*this));
1892 copy->plain_xml_ = uses_plain_xml<T>();
1893 return copy;
1894 }
1895
1896 void set_attr_value(const std::string& key, const std::string& value) override;
1897 AttrSetter make_attr_setter(const std::string& key) override;
1898 SVG* owner_svg();
1899 const SVG* owner_svg() const;
1900 void set_owner_svg(SVG* owner);
1901 void register_subtree_ids();
1902 void unregister_subtree_ids();
1903 void register_own_id();
1904 void unregister_own_id();
1905 void clear_children();
1906
1907 template<class T>
1908 T* insert_new_child(std::unique_ptr<T> child, ChildIterator position) {
1909 child->plain_xml_ = uses_plain_xml<T>();
1910 return static_cast<T*>(insert_child(std::move(child), position));
1911 }
1912
1913 Element* insert_child(std::unique_ptr<Element> child, ChildIterator position) {
1914 child->parent_ = this;
1915 child->set_owner_svg(this->owner_svg());
1916 try {
1917 child->register_subtree_ids();
1918 } catch (...) {
1919 child->unregister_subtree_ids();
1920 child->set_owner_svg(nullptr);
1921 child->parent_ = nullptr;
1922 throw;
1923 }
1924 return children.insert(position, std::move(child))->get();
1925 }
1926
1927 void reparent_children() {
1928 for (auto& child : children) {
1929 child->parent_ = this;
1930 child->set_owner_svg(this->owner_);
1931 child->reparent_children();
1932 }
1933 }
1934
1935 double find_numeric(const std::string& key) const {
1940 if (this->has_attr(key))
1941 return std::stof(this->get_attr(key));
1942 return NAN;
1943 }
1944
1945 private:
1946 template<class T> static bool uses_plain_xml();
1947 void append_plain_xml(std::string& out, size_t level) const;
1948 bool plain_xml_ = false;
1949 Element* parent_ = nullptr;
1950 SVG* owner_ = nullptr;
1951 std::string indexed_id_;
1952 bool has_layout_bbox_ = false;
1953 BoundingBox layout_bbox_ = BoundingBox(NAN, NAN, NAN, NAN);
1954 Margins layout_bbox_padding_ = NO_MARGINS;
1955 };
1956
1957 template<>
1958 inline Element::ChildList Element::get_immediate_children() {
1960 Element::ChildList ret;
1961 for (auto& child : this->children) ret.push_back(child.get());
1962 return ret;
1963 }
1964
1965 template<>
1966 inline Element::ConstChildList Element::get_immediate_children() const {
1968 Element::ConstChildList ret;
1969 for (auto& child : this->children) ret.push_back(child.get());
1970 return ret;
1971 }
1972
1973 inline Element* Element::get_element_by_id(const std::string &id) {
1975 auto child_elems = this->get_children_helper();
1976 for (auto& current: child_elems)
1977 if (current->id() == id) return current;
1978
1979 return nullptr;
1980 }
1981
1982 inline const Element* Element::get_element_by_id(const std::string &id) const {
1984 auto child_elems = this->get_children_helper();
1985 for (auto& current: child_elems)
1986 if (current->id() == id) return current;
1987
1988 return nullptr;
1989 }
1990
1991 inline std::vector<Element*> Element::get_elements_by_class(const std::string &clsname) {
1993 std::vector<Element*> ret;
1994 auto child_elems = this->get_children_helper();
1995
1996 for (auto& current: child_elems) {
1997 if (current->has_attr("class")
1998 && current->class_list().contains(clsname))
1999 ret.push_back(current);
2000 }
2001
2002 return ret;
2003 }
2004
2005 inline std::vector<const Element*> Element::get_elements_by_class(const std::string &clsname) const {
2007 std::vector<const Element*> ret;
2008 auto child_elems = this->get_children_helper();
2009
2010 for (auto& current: child_elems) {
2011 if (current->has_attr("class")
2012 && current->class_list().contains(clsname))
2013 ret.push_back(current);
2014 }
2015
2016 return ret;
2017 }
2018
2019 inline std::unique_ptr<Element> Element::clone_element() const {
2020 return this->clone_element_impl();
2021 }
2022
2023 inline Element::Element(const Element& other) :
2024 AttributeMap(other.attrs()),
2025 parent_(nullptr),
2026 owner_(nullptr),
2027 indexed_id_(),
2028 has_layout_bbox_(other.has_layout_bbox_),
2029 layout_bbox_(other.layout_bbox_),
2030 layout_bbox_padding_(other.layout_bbox_padding_) {
2031 for (const auto& child : other.children) {
2032 this->insert_child(child->clone_element(), this->children.end());
2033 }
2034 }
2035
2036 inline std::unique_ptr<Element> Element::clone_element_impl() const {
2037 throw std::logic_error("Custom SVG element subclasses must override clone_element_impl() to be cloned.");
2038 }
2039
2041 public:
2042 using iterator_category = std::input_iterator_tag;
2043 using value_type = Element*;
2044 using difference_type = std::ptrdiff_t;
2045 using pointer = Element**;
2046 using reference = Element*&;
2047
2048 DepthFirstIterator() = default;
2049 DepthFirstIterator(Element* root, bool include_root, TraversalOptions options = TraversalOptions()) :
2050 options_(options) {
2051 if (!root) return;
2052
2053 const auto root_transform = transform_for(root, detail::AffineTransform());
2054 if (include_root) {
2055 pending_.push_back(Frame(root, root_transform, true));
2056 } else {
2057 push_children(root, root_transform);
2058 }
2059 advance();
2060 }
2061
2062 Element* operator*() const { return current_.element; }
2063 const detail::AffineTransform& transform() const { return current_.transform; }
2064
2065 DepthFirstIterator& operator++() {
2066 advance();
2067 return *this;
2068 }
2069
2070 DepthFirstIterator operator++(int) {
2071 auto copy = *this;
2072 ++(*this);
2073 return copy;
2074 }
2075
2076 bool operator==(const DepthFirstIterator& other) const {
2077 if (end_ || other.end_) return end_ == other.end_;
2078 return current_.element == other.current_.element;
2079 }
2080
2081 bool operator!=(const DepthFirstIterator& other) const {
2082 return !(*this == other);
2083 }
2084
2085 private:
2086 struct Frame {
2087 Frame() : element(nullptr), transform(), root(false) {}
2088 Frame(Element* element, const detail::AffineTransform& transform, bool root = false) :
2089 element(element),
2090 transform(transform),
2091 root(root) {}
2092
2093 Element* element;
2094 detail::AffineTransform transform;
2095 bool root;
2096 };
2097
2098 static detail::AffineTransform transform_for(Element* element,
2099 const detail::AffineTransform& parent_transform) {
2100 if (element->has_attr("transform")) {
2101 return detail::multiply(parent_transform,
2102 detail::parse_supported_transform(element->get_attr("transform")));
2103 }
2104 return parent_transform;
2105 }
2106
2107 void push_children(Element* element, const detail::AffineTransform& transform) {
2108 for (auto child = element->children.rbegin(); child != element->children.rend(); ++child) {
2109 auto* child_ptr = child->get();
2110 pending_.push_back(Frame(child_ptr, transform_for(child_ptr, transform)));
2111 }
2112 }
2113
2114 void advance() {
2115 if (pending_.empty()) {
2116 current_ = Frame();
2117 end_ = true;
2118 return;
2119 }
2120
2121 current_ = pending_.back();
2122 pending_.pop_back();
2123 end_ = false;
2124 if (current_.root || options_.descend_into_nested_svgs ||
2125 current_.element->kind() != ElementKind::SVG) {
2126 push_children(current_.element, current_.transform);
2127 }
2128 }
2129
2130 std::vector<Frame> pending_;
2131 Frame current_;
2132 TraversalOptions options_;
2133 bool end_ = true;
2134 };
2135
2137 public:
2138 using iterator_category = std::input_iterator_tag;
2139 using value_type = const Element*;
2140 using difference_type = std::ptrdiff_t;
2141 using pointer = const Element**;
2142 using reference = const Element*&;
2143
2144 ConstDepthFirstIterator() = default;
2145 ConstDepthFirstIterator(const Element* root,
2146 bool include_root,
2147 TraversalOptions options = TraversalOptions()) :
2148 options_(options) {
2149 if (!root) return;
2150
2151 const auto root_transform = transform_for(root, detail::AffineTransform());
2152 if (include_root) {
2153 pending_.push_back(Frame(root, root_transform, true));
2154 } else {
2155 push_children(root, root_transform);
2156 }
2157 advance();
2158 }
2159
2160 const Element* operator*() const { return current_.element; }
2161 const detail::AffineTransform& transform() const { return current_.transform; }
2162
2163 ConstDepthFirstIterator& operator++() {
2164 advance();
2165 return *this;
2166 }
2167
2168 ConstDepthFirstIterator operator++(int) {
2169 auto copy = *this;
2170 ++(*this);
2171 return copy;
2172 }
2173
2174 bool operator==(const ConstDepthFirstIterator& other) const {
2175 if (end_ || other.end_) return end_ == other.end_;
2176 return current_.element == other.current_.element;
2177 }
2178
2179 bool operator!=(const ConstDepthFirstIterator& other) const {
2180 return !(*this == other);
2181 }
2182
2183 private:
2184 struct Frame {
2185 Frame() : element(nullptr), transform(), root(false) {}
2186 Frame(const Element* element, const detail::AffineTransform& transform, bool root = false) :
2187 element(element),
2188 transform(transform),
2189 root(root) {}
2190
2191 const Element* element;
2192 detail::AffineTransform transform;
2193 bool root;
2194 };
2195
2196 static detail::AffineTransform transform_for(const Element* element,
2197 const detail::AffineTransform& parent_transform) {
2198 if (element->has_attr("transform")) {
2199 return detail::multiply(parent_transform,
2200 detail::parse_supported_transform(element->get_attr("transform")));
2201 }
2202 return parent_transform;
2203 }
2204
2205 void push_children(const Element* element, const detail::AffineTransform& transform) {
2206 for (auto child = element->children.rbegin(); child != element->children.rend(); ++child) {
2207 const auto* child_ptr = child->get();
2208 pending_.push_back(Frame(child_ptr, transform_for(child_ptr, transform)));
2209 }
2210 }
2211
2212 void advance() {
2213 if (pending_.empty()) {
2214 current_ = Frame();
2215 end_ = true;
2216 return;
2217 }
2218
2219 current_ = pending_.back();
2220 pending_.pop_back();
2221 end_ = false;
2222 if (current_.root || options_.descend_into_nested_svgs ||
2223 current_.element->kind() != ElementKind::SVG) {
2224 push_children(current_.element, current_.transform);
2225 }
2226 }
2227
2228 std::vector<Frame> pending_;
2229 Frame current_;
2230 TraversalOptions options_;
2231 bool end_ = true;
2232 };
2233
2235 public:
2236 DepthFirstRange(Element* root, bool include_root, TraversalOptions options = TraversalOptions()) :
2237 root_(root), include_root_(include_root), options_(options) {}
2238
2239 DepthFirstIterator begin() const { return DepthFirstIterator(root_, include_root_, options_); }
2240 DepthFirstIterator end() const { return DepthFirstIterator(); }
2241
2242 private:
2243 Element* root_;
2244 bool include_root_;
2245 TraversalOptions options_;
2246 };
2247
2249 public:
2250 ConstDepthFirstRange(const Element* root,
2251 bool include_root,
2252 TraversalOptions options = TraversalOptions()) :
2253 root_(root), include_root_(include_root), options_(options) {}
2254
2255 ConstDepthFirstIterator begin() const { return ConstDepthFirstIterator(root_, include_root_, options_); }
2256 ConstDepthFirstIterator end() const { return ConstDepthFirstIterator(); }
2257
2258 private:
2259 const Element* root_;
2260 bool include_root_;
2261 TraversalOptions options_;
2262 };
2263
2265 return { this, true };
2266 }
2267
2269 return { this, true, options };
2270 }
2271
2273 return { this, true };
2274 }
2275
2277 return { this, true, options };
2278 }
2279
2281 return DepthFirstIterator(this, true);
2282 }
2283
2285 return ConstDepthFirstIterator(this, true);
2286 }
2287
2288 inline Element::DepthFirstIterator Element::end() {
2289 return DepthFirstIterator();
2290 }
2291
2292 inline Element::ConstDepthFirstIterator Element::end() const {
2293 return ConstDepthFirstIterator();
2294 }
2295
2297 return { this, false };
2298 }
2299
2301 return { this, false, options };
2302 }
2303
2305 return { this, false };
2306 }
2307
2309 return { this, false, options };
2310 }
2311
2314 return { NAN, NAN, NAN, NAN };
2315 }
2316
2320 class Shape: public Element {
2321 public:
2322 using Element::Element;
2323
2324 operator Point() const {
2326 return std::make_pair(this->x(), this->y());
2327 }
2328
2329 virtual std::vector<Point> points() const {
2331 auto bbox = this->get_bbox();
2332 return {
2333 Point(bbox.x1, bbox.y1), // Top left
2334 Point(bbox.x2, bbox.y1), // Top right
2335 Point(bbox.x1, bbox.y2), // Bottom left
2336 Point(bbox.x2, bbox.y2) // Bottom right
2337 };
2338 }
2339
2340 virtual double x() const { return this->find_numeric("x"); }
2341 virtual double y() const { return this->find_numeric("y"); }
2342 virtual double width() const {
2346 return this->find_numeric("width");
2347 }
2348 virtual double height() const {
2352 return this->find_numeric("height");
2353 }
2354 };
2355
2357 class Defs : public Element {
2358 public:
2359 static constexpr ElementKind static_kind = ElementKind::Defs;
2360 using Element::Element;
2361 ElementKind kind() const override { return static_kind; }
2363 LinearGradient& linear_gradient(std::string id);
2365 RadialGradient& radial_gradient(std::string id);
2367 Symbol* symbol(std::string id);
2368
2369 protected:
2370 std::unique_ptr<Element> clone_element_impl() const override { return clone_as<Defs>(); }
2371 };
2372
2374 namespace detail {
2376 class Stop : public Element {
2377 public:
2378 static constexpr ElementKind static_kind = ElementKind::Stop;
2379 Stop() = default;
2380 using Element::Element;
2381 ElementKind kind() const override { return static_kind; }
2382
2383 Stop(std::string offset, std::string color) {
2384 this->set_attr("offset", std::move(offset));
2385 this->set_attr("stop-color", std::move(color));
2386 }
2387
2388 Stop(std::string offset, std::string color, double opacity) :
2389 Stop(std::move(offset), std::move(color)) {
2390 this->set_attr("stop-opacity", opacity);
2391 }
2392
2393 protected:
2394 std::unique_ptr<Element> clone_element_impl() const override { return clone_as<Stop>(); }
2395 };
2396
2398 class GradientElement : public Element {
2399 public:
2400 using Element::Element;
2401
2403 std::string url() const {
2404 const auto gradient_id = this->id();
2405 if (gradient_id.empty()) {
2406 throw std::logic_error("SVG gradient must have an id before it can be referenced");
2407 }
2408 return "url(#" + gradient_id + ")";
2409 }
2410
2411 protected:
2412 void add_stop(std::string offset, std::string color) {
2413 this->add_child<Stop>(std::move(offset), std::move(color));
2414 }
2415
2416 void add_stop(std::string offset, std::string color, double opacity) {
2417 this->add_child<Stop>(std::move(offset), std::move(color), opacity);
2418 }
2419
2420 void set_solid_segments(std::initializer_list<std::string> colors) {
2421 if (colors.size() == 0) {
2422 throw std::invalid_argument("solid_segments requires at least one color");
2423 }
2424
2425 this->clear_children();
2426 if (colors.size() == 1) {
2427 const auto color = *colors.begin();
2428 add_stop("0%", color);
2429 add_stop("100%", color);
2430 return;
2431 }
2432
2433 const auto segment_width = 100.0 / static_cast<double>(colors.size());
2434 std::size_t index = 0;
2435 for (const auto& color : colors) {
2436 const auto start = percent(index * segment_width);
2437 const auto end = percent((index + 1) * segment_width);
2438 add_stop(start, color);
2439 add_stop(end, color);
2440 ++index;
2441 }
2442 }
2443
2444 private:
2445 static std::string percent(double value) {
2446 std::stringstream ss;
2447 ss << std::fixed << std::setprecision(1) << value << "%";
2448 return ss.str();
2449 }
2450 };
2451 }
2453
2455 class LinearGradient : public detail::GradientElement {
2456 public:
2457 static constexpr ElementKind static_kind = ElementKind::LinearGradient;
2458 LinearGradient() = default;
2459 using detail::GradientElement::GradientElement;
2460 ElementKind kind() const override { return static_kind; }
2461
2462 explicit LinearGradient(std::string id) {
2463 this->id(id);
2464 }
2465
2466 LinearGradient& horizontal() {
2467 return endpoints("0%", "0%", "100%", "0%");
2468 }
2469
2470 LinearGradient& vertical() {
2471 return endpoints("0%", "0%", "0%", "100%");
2472 }
2473
2474 LinearGradient& endpoints(std::string x1, std::string y1, std::string x2, std::string y2) {
2475 this->set_attr("x1", std::move(x1));
2476 this->set_attr("y1", std::move(y1));
2477 this->set_attr("x2", std::move(x2));
2478 this->set_attr("y2", std::move(y2));
2479 return *this;
2480 }
2481
2482 LinearGradient& stop(std::string offset, std::string color) {
2483 add_stop(std::move(offset), std::move(color));
2484 return *this;
2485 }
2486
2487 LinearGradient& stop(std::string offset, const Color& color) {
2488 return stop(std::move(offset), static_cast<std::string>(color));
2489 }
2490
2491 LinearGradient& stop(std::string offset, std::string color, double opacity) {
2492 add_stop(std::move(offset), std::move(color), opacity);
2493 return *this;
2494 }
2495
2496 LinearGradient& stop(std::string offset, const Color& color, double opacity) {
2497 return stop(std::move(offset), static_cast<std::string>(color), opacity);
2498 }
2499
2500 LinearGradient& solid_segments(std::initializer_list<std::string> colors) {
2501 set_solid_segments(colors);
2502 return *this;
2503 }
2504
2505 protected:
2506 std::unique_ptr<Element> clone_element_impl() const override { return clone_as<LinearGradient>(); }
2507 };
2508
2510 class RadialGradient : public detail::GradientElement {
2511 public:
2512 static constexpr ElementKind static_kind = ElementKind::RadialGradient;
2513 RadialGradient() = default;
2514 using detail::GradientElement::GradientElement;
2515 ElementKind kind() const override { return static_kind; }
2516
2517 explicit RadialGradient(std::string id) {
2518 this->id(id);
2519 }
2520
2521 RadialGradient& center(std::string cx, std::string cy) {
2522 this->set_attr("cx", std::move(cx));
2523 this->set_attr("cy", std::move(cy));
2524 return *this;
2525 }
2526
2527 RadialGradient& radius(std::string r) {
2528 this->set_attr("r", std::move(r));
2529 return *this;
2530 }
2531
2532 RadialGradient& focal(std::string fx, std::string fy) {
2533 this->set_attr("fx", std::move(fx));
2534 this->set_attr("fy", std::move(fy));
2535 return *this;
2536 }
2537
2538 RadialGradient& stop(std::string offset, std::string color) {
2539 add_stop(std::move(offset), std::move(color));
2540 return *this;
2541 }
2542
2543 RadialGradient& stop(std::string offset, const Color& color) {
2544 return stop(std::move(offset), static_cast<std::string>(color));
2545 }
2546
2547 RadialGradient& stop(std::string offset, std::string color, double opacity) {
2548 add_stop(std::move(offset), std::move(color), opacity);
2549 return *this;
2550 }
2551
2552 RadialGradient& stop(std::string offset, const Color& color, double opacity) {
2553 return stop(std::move(offset), static_cast<std::string>(color), opacity);
2554 }
2555
2556 RadialGradient& solid_segments(std::initializer_list<std::string> colors) {
2557 set_solid_segments(colors);
2558 return *this;
2559 }
2560
2561 protected:
2562 std::unique_ptr<Element> clone_element_impl() const override { return clone_as<RadialGradient>(); }
2563 };
2564
2566 class Symbol : public Element {
2567 public:
2568 static constexpr ElementKind static_kind = ElementKind::Symbol;
2569 Symbol() = default;
2570 using Element::Element;
2571
2572 explicit Symbol(std::string id) {
2573 this->id(id);
2574 }
2575
2577 std::string href() const;
2578 ElementKind kind() const override { return static_kind; }
2580 Element::BoundingBox get_bbox() const override;
2582 Use use(double x, double y) const;
2584 Use use(double x, double y, double width, double height) const;
2585
2586 protected:
2587 std::unique_ptr<Element> clone_element_impl() const override { return clone_as<Symbol>(); }
2588 };
2589
2591 class Use : public Shape {
2592 public:
2593 static constexpr ElementKind static_kind = ElementKind::Use;
2594 Use() = default;
2595 using Shape::Shape;
2596
2597 explicit Use(std::string href) {
2598 set_attr("href", std::move(href));
2599 }
2600
2601 Use(std::string href, double x, double y) : Use(std::move(href)) {
2602 set_attr("x", x);
2603 set_attr("y", y);
2604 }
2605
2606 Use(std::string href, double x, double y, double width, double height) :
2607 Use(std::move(href), x, y) {
2608 set_attr("width", width);
2609 set_attr("height", height);
2610 }
2611
2613 Use& xlink_href(std::string href) {
2614 set_attr("xlink:href", std::move(href));
2615 return *this;
2616 }
2617 ElementKind kind() const override { return static_kind; }
2619 Element::BoundingBox get_bbox() const override;
2620
2621 protected:
2622 std::unique_ptr<Element> clone_element_impl() const override { return clone_as<Use>(); }
2623 };
2624
2625 class SVG : public Shape {
2626 friend class Element;
2627
2628 std::map<std::string, Element*> id_index_;
2629 Defs* defs_ = nullptr;
2630
2631 public:
2632 class Style : public Element {
2633 public:
2634 static constexpr ElementKind static_kind = ElementKind::Style;
2635 Style() = default;
2636 using Element::Element;
2638 std::map<std::string, SelectorProperties> media_queries;
2639 std::map<std::string, SelectorProperties> keyframes;
2640 ElementKind kind() const override { return static_kind; }
2641
2642 protected:
2643 std::string svg_to_string(const size_t) const override;
2644 std::unique_ptr<Element> clone_element_impl() const override;
2645 };
2646
2647 static constexpr ElementKind static_kind = ElementKind::SVG;
2649 SVG(SVGAttrib _attr =
2650 { { "xmlns", "http://www.w3.org/2000/svg" } }
2651 ) : Shape(_attr) {
2652 set_owner_svg(this);
2653 rebuild_id_index();
2654 };
2655
2657 SVG(const SVG& other) : Shape(other.attrs()), id_index_(), defs_(nullptr), css(nullptr) {
2658 clone_children_from(other);
2659 refresh_special_children();
2660 set_owner_svg(this);
2661 rebuild_id_index();
2662 }
2663
2664 SVG(SVG&& other) noexcept :
2665 Shape(std::move(other)),
2666 id_index_(std::move(other.id_index_)),
2667 defs_(nullptr),
2668 css(nullptr) {
2669 refresh_special_children();
2670 set_owner_svg(this);
2671 rebuild_id_index();
2672 }
2673
2674 SVG& operator=(SVG&& other) noexcept {
2675 if (this != &other) {
2676 Shape::operator=(std::move(other));
2677 id_index_ = std::move(other.id_index_);
2678 defs_ = nullptr;
2679 css = nullptr;
2680 refresh_special_children();
2681 set_owner_svg(this);
2682 rebuild_id_index();
2683 }
2684 return *this;
2685 }
2686
2687 SVG& operator=(const SVG& other) = delete;
2688
2690 SVG clone() const {
2691 return SVG(*this);
2692 }
2693
2695 AttributeMap& style(const std::string& key) { return this->css->css[key]; }
2696
2698 SVG& style(const std::string& key, const Attrs& attrs) {
2699 this->style(key).set_attrs(attrs);
2700 return *this;
2701 }
2702
2704 AttributeMap& media_style(const std::string& query, const std::string& key) {
2705 return this->css->media_queries[query][key];
2706 }
2707
2709 SVG& media_style(const std::string& query, const std::string& key, const Attrs& attrs) {
2710 this->media_style(query, key).set_attrs(attrs);
2711 return *this;
2712 }
2713
2715 template<typename T>
2716 Variables<T> set_vars(std::initializer_list<VariableSpec<T>> specs) {
2717 return this->set_vars<T>(":root", specs);
2718 }
2719
2721 template<typename T>
2722 Variables<T> set_vars(const std::string& selector, std::initializer_list<VariableSpec<T>> specs) {
2723 return Variables<T>(this->style(selector), specs);
2724 }
2725
2727 template<typename T>
2728 Variables<T> set_vars(const std::string& query,
2729 const std::string& selector,
2730 std::initializer_list<VariableSpec<T>> specs) {
2731 return Variables<T>(this->media_style(query, selector), specs);
2732 }
2733
2734 std::map<std::string, AttributeMap>& keyframes(const std::string& key) {
2739 if (!this->css) this->css = this->add_child<Style>();
2740 return this->css->keyframes[key];
2741 }
2742
2745 if (!this->defs_) this->defs_ = this->add_child<Defs>();
2746 return this->defs_;
2747 }
2748
2749 template<typename T, typename... Args>
2750 typename std::enable_if<!std::is_same<T, Defs>::value, T*>::type add_child(Args&&... args) {
2751 return Element::add_child<T>(std::forward<Args>(args)...);
2752 }
2753
2754 template<typename T, typename... Args>
2755 typename std::enable_if<std::is_same<T, Defs>::value, T*>::type add_child(Args&&... args) {
2756 if (this->defs_) return this->defs_;
2757
2758 auto child = detail::make_child<T>(std::forward<Args>(args)...);
2759 auto* inserted = this->insert_new_child(std::move(child), this->defs_insert_position());
2760 this->defs_ = inserted;
2761 return inserted;
2762 }
2763
2764 Element* get_element_by_id(const std::string& id) {
2765 const auto found = this->id_index_.find(id);
2766 return found == this->id_index_.end() ? nullptr : found->second;
2767 }
2768
2769 const Element* get_element_by_id(const std::string& id) const {
2770 const auto found = this->id_index_.find(id);
2771 return found == this->id_index_.end() ? nullptr : found->second;
2772 }
2773
2775 template<typename T>
2776 T* get_element_by_id(const std::string& id) {
2777 SVG_TYPE_CHECK;
2778 auto* element = this->get_element_by_id(id);
2779 if (!element || element->kind() != T::static_kind) return nullptr;
2780 return static_cast<T*>(element);
2781 }
2782
2784 template<typename T>
2785 const T* get_element_by_id(const std::string& id) const {
2786 SVG_TYPE_CHECK;
2787 auto* element = this->get_element_by_id(id);
2788 if (!element || element->kind() != T::static_kind) return nullptr;
2789 return static_cast<const T*>(element);
2790 }
2791
2792 Style* css = this->add_child<Style>();
2793 ElementKind kind() const override { return static_kind; }
2795 BoundingBox get_bbox() const override;
2796
2797 protected:
2798 std::unique_ptr<Element> clone_element_impl() const override {
2799 return detail::make_unique<SVG>(*this);
2800 }
2801
2802 private:
2803 void clone_children_from(const SVG& other) {
2804 for (const auto& child : other.children) {
2805 this->insert_child(child->clone_element(), this->children.end());
2806 }
2807 }
2808
2809 void refresh_special_children() {
2810 this->css = nullptr;
2811 this->defs_ = nullptr;
2812 for (auto& child : this->children) {
2813 if (child->kind() == Style::static_kind) {
2814 this->css = static_cast<Style*>(child.get());
2815 } else if (child->kind() == Defs::static_kind) {
2816 this->defs_ = static_cast<Defs*>(child.get());
2817 }
2818 }
2819 }
2820
2821 void register_id(Element& element, const std::string& id) {
2822 if (id.empty()) return;
2823 const auto found = this->id_index_.find(id);
2824 if (found != this->id_index_.end() && found->second != &element) {
2825 throw std::invalid_argument("Duplicate SVG element id: " + id);
2826 }
2827 this->id_index_[id] = &element;
2828 }
2829
2830 void unregister_id(Element& element, const std::string& id) {
2831 if (id.empty()) return;
2832 const auto found = this->id_index_.find(id);
2833 if (found != this->id_index_.end() && found->second == &element) {
2834 this->id_index_.erase(found);
2835 }
2836 }
2837
2838 void rebuild_id_index() {
2839 this->id_index_.clear();
2840 this->register_subtree_ids();
2841 }
2842
2843 ChildIterator defs_insert_position() {
2844 if (!this->css) return this->children.begin();
2845
2846 for (auto it = this->children.begin(); it != this->children.end(); ++it) {
2847 if (it->get() == this->css) return it + 1;
2848 }
2849 return this->children.begin();
2850 }
2851
2852 };
2853
2854 inline SVG* Element::owner_svg() {
2855 return this->owner_;
2856 }
2857
2858 inline const SVG* Element::owner_svg() const {
2859 return this->owner_;
2860 }
2861
2862 inline void Element::set_owner_svg(SVG* owner) {
2863 this->owner_ = owner;
2864 for (auto& child : this->children) {
2865 child->set_owner_svg(owner);
2866 }
2867 }
2868
2869 inline Element& Element::id(const std::string& value) {
2870 const auto old_indexed_id = this->indexed_id_;
2871 auto* root = this->owner_svg();
2872
2873 if (value.empty()) {
2874 if (root && !old_indexed_id.empty()) {
2875 root->unregister_id(*this, old_indexed_id);
2876 }
2877 this->mutable_attrs().erase("id");
2878 this->indexed_id_.clear();
2879 return *this;
2880 }
2881
2882 if (root && old_indexed_id != value) {
2883 root->register_id(*this, value);
2884 }
2885 if (root && !old_indexed_id.empty() && old_indexed_id != value) {
2886 root->unregister_id(*this, old_indexed_id);
2887 }
2888
2889 this->mutable_attrs()["id"] = value;
2890 this->indexed_id_ = root ? value : "";
2891 return *this;
2892 }
2893
2894 inline std::string Element::id() const {
2895 return this->get_attr("id");
2896 }
2897
2898 inline void Element::set_attr_value(const std::string& key, const std::string& value) {
2899 if (key == "id") {
2900 this->id(value);
2901 return;
2902 }
2903 AttributeMap::set_attr_value(key, value);
2904 }
2905
2906 inline AttributeMap::AttrSetter Element::make_attr_setter(const std::string& key) {
2907 if (key != "id") {
2908 return AttributeMap::make_attr_setter(key);
2909 }
2910
2911 this->id("");
2912 this->mutable_attrs()[key] = "";
2913 return AttrSetter(this->mutable_attrs().at(key), false, [this](const std::string& value) {
2914 const auto previous = this->indexed_id_;
2915 try {
2916 this->id(value);
2917 } catch (...) {
2918 if (previous.empty()) {
2919 this->mutable_attrs().erase("id");
2920 } else {
2921 this->mutable_attrs()["id"] = previous;
2922 }
2923 throw;
2924 }
2925 });
2926 }
2927
2928 inline void Element::register_subtree_ids() {
2929 this->register_own_id();
2930 for (auto& child : this->children) {
2931 child->register_subtree_ids();
2932 }
2933 }
2934
2935 inline void Element::unregister_subtree_ids() {
2936 this->unregister_own_id();
2937 for (auto& child : this->children) {
2938 child->unregister_subtree_ids();
2939 }
2940 }
2941
2942 inline void Element::register_own_id() {
2943 const auto current_id = this->id();
2944 if (current_id.empty()) return;
2945
2946 if (auto* root = this->owner_svg()) {
2947 root->register_id(*this, current_id);
2948 this->indexed_id_ = current_id;
2949 }
2950 }
2951
2952 inline void Element::unregister_own_id() {
2953 if (this->indexed_id_.empty()) return;
2954
2955 if (auto* root = this->owner_svg()) {
2956 root->unregister_id(*this, this->indexed_id_);
2957 }
2958 this->indexed_id_.clear();
2959 }
2960
2961 inline void Element::clear_children() {
2962 for (auto& child : this->children) {
2963 child->unregister_subtree_ids();
2964 child->set_owner_svg(nullptr);
2965 child->parent_ = nullptr;
2966 }
2967 this->children.clear();
2968 }
2969
2970 inline LinearGradient& Defs::linear_gradient(std::string id) {
2971 for (auto* child : this->get_immediate_children<LinearGradient>()) {
2972 if (child->id() == id) return *child;
2973 }
2974 return *this->add_child<LinearGradient>(std::move(id));
2975 }
2976
2977 inline RadialGradient& Defs::radial_gradient(std::string id) {
2978 for (auto* child : this->get_immediate_children<RadialGradient>()) {
2979 if (child->id() == id) return *child;
2980 }
2981 return *this->add_child<RadialGradient>(std::move(id));
2982 }
2983
2984 inline Symbol* Defs::symbol(std::string id) {
2985 for (auto* child : this->get_immediate_children<Symbol>()) {
2986 if (child->id() == id) return child;
2987 }
2988 return this->add_child<Symbol>(std::move(id));
2989 }
2990
2991 inline std::string Symbol::href() const {
2992 const auto symbol_id = this->id();
2993 if (symbol_id.empty()) {
2994 throw std::logic_error("SVG symbol must have an id before it can be referenced");
2995 }
2996 return "#" + symbol_id;
2997 }
2998
3000 Element::BoundingBox bbox(NAN, NAN, NAN, NAN);
3001 this->Element::get_bbox(bbox, false);
3002 return bbox;
3003 }
3004
3005 inline Use Symbol::use(double x, double y) const {
3006 return Use(this->href(), x, y);
3007 }
3008
3009 inline Use Symbol::use(double x, double y, double width, double height) const {
3010 return Use(this->href(), x, y, width, height);
3011 }
3012
3013 class Path : public Shape {
3014 public:
3015 static constexpr ElementKind static_kind = ElementKind::Path;
3016 using Shape::Shape;
3017 ElementKind kind() const override { return static_kind; }
3018
3019 template<typename T>
3020 inline void start(T x, T y) {
3024 this->set_attr("d", "M " + std::to_string(x) + " " + std::to_string(y));
3025 this->x_start = x;
3026 this->y_start = y;
3027 }
3028
3029 template<typename T>
3030 inline void line_to(T x, T y) {
3035
3036 if (!this->has_attr("d"))
3037 start(x, y);
3038 else
3039 this->mutable_attrs()["d"] += " L " + std::to_string(x) +
3040 " " + std::to_string(y);
3041 }
3042
3043 inline void line_to(std::pair<double, double> coord) {
3044 this->line_to(coord.first, coord.second);
3045 }
3046
3047 inline void to_origin() {
3049 this->line_to(x_start, y_start);
3050 }
3051
3052 protected:
3053 std::unique_ptr<Element> clone_element_impl() const override {
3054 return clone_as<Path>();
3055 }
3056
3057 private:
3058 double x_start = 0;
3059 double y_start = 0;
3060 };
3061
3063 class Text : public Element {
3064 public:
3065 static constexpr ElementKind static_kind = ElementKind::Text;
3066 Text() = default;
3067 using Element::Element;
3068 ElementKind kind() const override { return static_kind; }
3069
3070 Text(double x, double y, std::string _content) {
3071 set_attr("x", to_string(x));
3072 set_attr("y", to_string(y));
3073 content = _content;
3074 }
3075
3076 Text(std::pair<double, double> xy, std::string _content) :
3077 Text(xy.first, xy.second, _content) {};
3078
3080 BoundingBox get_bbox() const override;
3081
3082 protected:
3083 std::string content;
3084 std::string svg_to_string(const size_t) const override;
3085 std::unique_ptr<Element> clone_element_impl() const override {
3086 return clone_as<Text>();
3087 }
3088 };
3089
3091 class Title : public Element {
3092 public:
3094 static constexpr ElementKind static_kind = ElementKind::Title;
3095 Title() = default;
3097 explicit Title(const char* _content) : content(_content) {}
3099 explicit Title(std::string _content) : content(std::move(_content)) {}
3100 ElementKind kind() const override { return static_kind; }
3101
3102 protected:
3104 std::string content;
3106 std::string svg_to_string(const size_t) const override;
3107 std::unique_ptr<Element> clone_element_impl() const override {
3108 return clone_as<Title>();
3109 }
3110 };
3111
3112 class Group : public Element {
3113 public:
3114 static constexpr ElementKind static_kind = ElementKind::Group;
3115 using Element::Element;
3116 ElementKind kind() const override { return static_kind; }
3117
3118 protected:
3119 std::unique_ptr<Element> clone_element_impl() const override { return clone_as<Group>(); }
3120 };
3121
3123 using G = Group;
3124
3125 class Line : public Shape {
3126 public:
3127 static constexpr ElementKind static_kind = ElementKind::Line;
3128 Line() = default;
3129 using Shape::Shape;
3130 ElementKind kind() const override { return static_kind; }
3131
3132 Line(double x1, double x2, double y1, double y2) : Shape({
3133 { "x1", to_string(x1) },
3134 { "x2", to_string(x2) },
3135 { "y1", to_string(y1) },
3136 { "y2", to_string(y2) }
3137 }) {};
3138
3139 Line(Point x, Point y) : Line(x.first, y.first, x.second, y.second) {};
3140
3141 virtual double x() const override { return x1() + (x2() - x1()) / 2; }
3142 virtual double y() const override { return y1() + (y2() - y1()) / 2; }
3143 double x1() const { return this->find_numeric("x1"); }
3144 double x2() const { return this->find_numeric("x2"); }
3145 double y1() const { return this->find_numeric("y1"); }
3146 double y2() const { return this->find_numeric("y2"); }
3147
3148 double width() const override { return std::abs(x2() - x1()); }
3149 double height() const override { return std::abs(y2() - y1()); }
3150 double length() const { return std::sqrt(pow(width(), 2) + pow(height(), 2)); }
3151 double slope() const { return (y2() - y1()) / (x2() - x1()); }
3152 double angle() const { return atan(this->slope()) * RAD_TO_DEG; }
3153
3154 std::pair<double, double> along(double percent) const;
3155
3156 protected:
3157 Element::BoundingBox get_bbox() const override;
3158 std::unique_ptr<Element> clone_element_impl() const override { return clone_as<Line>(); }
3159 };
3160
3161 class Rect : public Shape {
3162 public:
3163 static constexpr ElementKind static_kind = ElementKind::Rect;
3164 Rect() = default;
3165 using Shape::Shape;
3166 ElementKind kind() const override { return static_kind; }
3167
3168 Rect(
3169 double x, double y, double width, double height) :
3170 Shape({
3171 { "x", to_string(x) },
3172 { "y", to_string(y) },
3173 { "width", to_string(width) },
3174 { "height", to_string(height) }
3175 }) {};
3176
3177 Element::BoundingBox get_bbox() const override;
3178
3179 protected:
3180 std::unique_ptr<Element> clone_element_impl() const override { return clone_as<Rect>(); }
3181 };
3182
3183 class Circle : public Shape {
3184 public:
3185 static constexpr ElementKind static_kind = ElementKind::Circle;
3186 Circle() = default;
3187 using Shape::Shape;
3188 ElementKind kind() const override { return static_kind; }
3189
3190 Circle(double cx, double cy, double radius) :
3191 Shape({
3192 { "cx", to_string(cx) },
3193 { "cy", to_string(cy) },
3194 { "r", to_string(radius) }
3195 }) {
3196 };
3197
3198 Circle(std::pair<double, double> xy, double radius) : Circle(xy.first, xy.second, radius) {};
3199 double radius() const { return this->find_numeric("r"); }
3200 virtual double x() const override { return this->find_numeric("cx"); }
3201 virtual double y() const override { return this->find_numeric("cy"); }
3202 virtual double width() const override { return this->radius() * 2; }
3203 virtual double height() const override { return this->width(); }
3204 Element::BoundingBox get_bbox() const override;
3205
3206 protected:
3207 std::unique_ptr<Element> clone_element_impl() const override { return clone_as<Circle>(); }
3208 };
3209
3210 class Polygon : public Element {
3211 public:
3212 static constexpr ElementKind static_kind = ElementKind::Polygon;
3213 Polygon() = default;
3214 using Element::Element;
3215 ElementKind kind() const override { return static_kind; }
3216
3217 Polygon(const std::vector<Point>& points) {
3218 // Quick and dirty
3219 std::string point_str;
3220 for (auto& pt : points)
3221 point_str += to_string(pt) + " ";
3222 this->set_attr("points", point_str);
3223 };
3224
3225 protected:
3226 std::unique_ptr<Element> clone_element_impl() const override { return clone_as<Polygon>(); }
3227 };
3228
3230 if (content.empty()) {
3231 const auto x = get_attr<double>("x", 0) + get_attr<double>("dx", 0);
3232 const auto y = get_attr<double>("y", 0) + get_attr<double>("dy", 0);
3233 return include_stroke_width({ x, x, y, y });
3234 }
3235
3236 double font_size = get_attr<double>("font-size", 16);
3237 if (!(font_size > 0)) font_size = 16;
3238
3239 const double x = get_attr<double>("x", 0) + get_attr<double>("dx", 0);
3240 const double y = get_attr<double>("y", 0) + get_attr<double>("dy", 0);
3241 const auto metrics = detail::TextEstimator(content, font_size, get_attr("font-weight")).estimate();
3242 const double width = metrics.width;
3243 const double height = metrics.height;
3244
3245 double x1 = x;
3246 const auto anchor = this->get_attr("text-anchor", "start");
3247 if (anchor == "middle") {
3248 x1 = x - width / 2;
3249 } else if (anchor == "end") {
3250 x1 = x - width;
3251 }
3252
3253 const auto baseline = this->get_attr(
3254 "dominant-baseline",
3255 this->get_attr("alignment-baseline", "alphabetic"));
3256 double y1 = y - metrics.ascent;
3257 if (baseline == "middle" || baseline == "central" || baseline == "mathematical") {
3258 y1 = y - height / 2;
3259 } else if (baseline == "hanging" || baseline == "text-before-edge" || baseline == "text-top") {
3260 y1 = y;
3261 } else if (baseline == "text-after-edge" || baseline == "text-bottom") {
3262 y1 = y - height;
3263 }
3264
3265 return include_stroke_width({ x1, x1 + width, y1, y1 + height });
3266 }
3267
3268 inline Element::BoundingBox Line::get_bbox() const {
3269 return include_stroke_width({ std::min(x1(), x2()), std::max(x1(), x2()),
3270 std::min(y1(), y2()), std::max(y1(), y2()) });
3271 }
3272
3273 inline Element::BoundingBox Rect::get_bbox() const {
3274 double x = this->x(), y = this->y(),
3275 width = this->width(), height = this->height();
3276 return include_stroke_width({ x, x + width, y, y + height });
3277 }
3278
3279 inline Element::BoundingBox Circle::get_bbox() const {
3280 double x = this->x(), y = this->y(), radius = this->radius();
3281
3282 return include_stroke_width({
3283 x - radius,
3284 x + radius,
3285 y - radius,
3286 y + radius
3287 });
3288 }
3289
3290 inline std::pair<double, double> Line::along(double percent) const {
3294
3295 double x_pos, y_pos;
3296
3297 if (x1() != x2()) {
3298 double length = percent * this->length();
3299 double discrim = std::sqrt(4 * pow(length, 2) * (1 / (1 + pow(slope(), 2))));
3300
3301 double x_a = (2 * x1() + discrim) / 2;
3302 double x_b = (2 * x1() - discrim) / 2;
3303 x_pos = x_a;
3304
3305 if ((x_a > x1() && x_a > x2()) || (x_a < x1() && x_a < x2()))
3306 x_pos = x_b;
3307
3308 y_pos = slope() * (x_pos - x1()) + y1();
3309 }
3310 else { // Edge case:: Completely vertical lines
3311 x_pos = x1();
3312
3313 if (y1() > y2()) // Downward pointing
3314 y_pos = y1() - percent * this->length();
3315 else
3316 y_pos = y1() + percent * this->length();
3317 }
3318
3319 return std::make_pair(x_pos, y_pos);
3320 }
3321
3322 namespace detail {
3323 inline void append_open_tag(std::string& out, size_t level, const std::string& tag,
3324 const SVGAttrib& attrs) {
3325 out.append(level, '\t');
3326 out += '<';
3327 out += tag;
3328 for (const auto& pair : attrs) {
3329 out += ' ';
3330 out += pair.first;
3331 out += "=\"";
3332 append_escaped_xml(out, pair.second);
3333 out += '"';
3334 }
3335 }
3336
3338 inline std::string text_content_element_to_string(const Element& element,
3339 const std::string& tag,
3340 const std::string& content,
3341 const size_t indent_level) {
3342 std::string out;
3343 append_open_tag(out, indent_level, tag, element.attrs());
3344 out += '>';
3345 append_escaped_xml(out, content);
3346 out += "</";
3347 out += tag;
3348 out += '>';
3349 return out;
3350 }
3351 }
3352
3353 template<class T>
3354 inline bool Element::uses_plain_xml() {
3355 // Only exact built-in types with ordinary tag serialization can skip virtual
3356 // svg_to_string(). Subclasses can override it even when they inherit kind().
3357 return std::is_same<T, SVG>::value || std::is_same<T, Group>::value ||
3358 std::is_same<T, Use>::value || std::is_same<T, Path>::value ||
3359 std::is_same<T, Line>::value || std::is_same<T, Rect>::value ||
3360 std::is_same<T, Circle>::value || std::is_same<T, Polygon>::value ||
3361 std::is_same<T, Defs>::value || std::is_same<T, Symbol>::value ||
3362 std::is_same<T, LinearGradient>::value || std::is_same<T, RadialGradient>::value ||
3363 std::is_same<T, detail::Stop>::value;
3364 }
3365
3366 inline void Element::append_plain_xml(std::string& out, size_t level) const {
3367 const auto name = tag();
3368 detail::append_open_tag(out, level, name, attrs());
3369 if (children.empty()) {
3370 out += " />";
3371 return;
3372 }
3373 out += ">\n";
3374 for (const auto& child : children) {
3375 const auto start = out.size();
3376 if (child->plain_xml_)
3377 child->append_plain_xml(out, level + 1);
3378 else
3379 out += child->svg_to_string(level + 1);
3380 if (out.size() != start) out += '\n';
3381 }
3382 out.append(level, '\t');
3383 out += "</";
3384 out += name;
3385 out += '>';
3386 }
3387
3388 inline std::string Element::svg_to_string(size_t level) const {
3389 std::string out;
3390 append_plain_xml(out, level);
3391 return out;
3392 }
3393
3394 inline std::string to_string(const std::map<std::string, AttributeMap>& css, const size_t indent_level) {
3396 auto indent = std::string(indent_level, '\t'), ret = std::string();
3397 for (auto& selector : css) {
3398 // Loop over each selector's attribute/value pairs
3399 ret += indent + "\t\t" + selector.first + " {\n";
3400 for (auto& attr : selector.second.attrs())
3401 ret += indent + "\t\t\t" + attr.first + ": " + attr.second + ";\n";
3402 ret += indent + "\t\t" + "}\n";
3403 }
3404 return ret;
3405 }
3406
3407 inline std::string SVG::Style::svg_to_string(const size_t indent_level) const {
3409 auto indent = std::string(indent_level, '\t');
3410
3411 if (!this->css.empty() || !this->media_queries.empty() || !this->keyframes.empty()) {
3412 std::string ret = indent + "<style type=\"text/css\">\n" +
3413 indent + "\t<![CDATA[\n";
3414
3415 // Begin CSS stylesheet
3416 ret += to_string(this->css, indent_level);
3417
3418 // Media queries
3419 for (auto& media : this->media_queries) {
3420 ret += indent + "\t\t@media " + media.first + " {\n" +
3421 to_string(media.second, indent_level + 1) +
3422 indent + "\t\t" + "}\n";
3423 }
3424
3425 // Animation frames
3426 for (auto& anim : this->keyframes) {
3427 ret += indent + "\t\t@keyframes " + anim.first + " {\n" +
3428 to_string(anim.second, indent_level + 1) +
3429 indent + "\t\t" + "}\n";
3430 }
3431
3432 ret += indent + "\t]]>\n";
3433 return ret + indent + "</style>";
3434 }
3435
3436 return "";
3437 }
3438
3439 inline std::unique_ptr<Element> SVG::Style::clone_element_impl() const {
3440 return clone_as<Style>();
3441 }
3442
3443 inline std::string Text::svg_to_string(const size_t indent_level) const {
3444 return detail::text_content_element_to_string(*this, tag_name(this->kind()), this->content, indent_level);
3445 }
3446
3447 inline std::string Title::svg_to_string(const size_t indent_level) const {
3448 return detail::text_content_element_to_string(*this, tag_name(this->kind()), this->content, indent_level);
3449 }
3450
3451 inline Element& Element::layout_bbox(const BoundingBox& bbox) {
3452 layout_bbox_ = bbox;
3453 has_layout_bbox_ = true;
3454 return *this;
3455 }
3456
3457 inline Element& Element::bbox_padding(const Margins& padding) {
3458 layout_bbox_padding_ = padding;
3459 return *this;
3460 }
3461
3462 inline Element& Element::bbox_padding(double padding) {
3463 return bbox_padding({ padding, padding, padding, padding });
3464 }
3465
3466 inline Element& Element::clear_layout_bbox() {
3467 has_layout_bbox_ = false;
3468 layout_bbox_ = BoundingBox(NAN, NAN, NAN, NAN);
3469 return *this;
3470 }
3471
3473 return measured_layout_bbox();
3474 }
3475
3476 inline Element::BoundingBox Element::measured_layout_bbox() const {
3477 if (has_layout_bbox_) return layout_bbox_;
3478 auto bbox = this->get_bbox();
3479 if (std::isnan(bbox.x1) || std::isnan(bbox.x2) ||
3480 std::isnan(bbox.y1) || std::isnan(bbox.y2)) {
3481 return bbox;
3482 }
3483 return {
3484 bbox.x1 - layout_bbox_padding_.x1,
3485 bbox.x2 + layout_bbox_padding_.x2,
3486 bbox.y1 - layout_bbox_padding_.y1,
3487 bbox.y2 + layout_bbox_padding_.y2
3488 };
3489 }
3490
3491 inline detail::AffineTransform Element::transform_for(
3492 const Element* element,
3493 const detail::AffineTransform& parent_transform) {
3494 if (element->has_attr("transform")) {
3495 return detail::multiply(parent_transform,
3496 detail::parse_supported_transform(element->get_attr("transform")));
3497 }
3498 return parent_transform;
3499 }
3500
3501 namespace detail {
3502 inline unsigned alignment_count_bits(Alignment value) {
3503 unsigned count = 0;
3504 while (value) {
3505 count += value & 1u;
3506 value >>= 1u;
3507 }
3508 return count;
3509 }
3510
3511 inline bool bbox_is_measured(const Element::BoundingBox& bbox) {
3512 return !(std::isnan(bbox.x1) || std::isnan(bbox.x2) ||
3513 std::isnan(bbox.y1) || std::isnan(bbox.y2));
3514 }
3515
3516 inline double visible_stroke_width(const Element& element) {
3517 const auto stroke = element.get_attr("stroke");
3518 if (stroke.empty() || stroke == "none") return 0;
3519
3520 const auto width = element.get_attr<double>("stroke-width", 1);
3521 return width > 0 ? width : 0;
3522 }
3523
3524 inline bool renders_in_place(const Element* element) {
3525 for (auto* current = element; current; current = current->parent()) {
3526 const auto kind = current->kind();
3527 if (kind == ElementKind::Defs || kind == ElementKind::Style ||
3528 kind == ElementKind::Symbol ||
3529 kind == ElementKind::LinearGradient ||
3530 kind == ElementKind::RadialGradient ||
3531 kind == ElementKind::Stop) {
3532 return false;
3533 }
3534 }
3535 return true;
3536 }
3537
3538 inline double bbox_center_x(const Element::BoundingBox& bbox) {
3539 return bbox.x1 + (bbox.x2 - bbox.x1) / 2;
3540 }
3541
3542 inline double bbox_center_y(const Element::BoundingBox& bbox) {
3543 return bbox.y1 + (bbox.y2 - bbox.y1) / 2;
3544 }
3545
3546 inline double bbox_anchor_x(const Element::BoundingBox& bbox, Anchor anchor) {
3547 if (anchor == Anchor::Start) return bbox.x1;
3548 if (anchor == Anchor::Center) return bbox_center_x(bbox);
3549 if (anchor == Anchor::End) return bbox.x2;
3550 throw std::invalid_argument("rotate_about_bbox requires a valid x anchor");
3551 }
3552
3553 inline double bbox_anchor_y(const Element::BoundingBox& bbox, Anchor anchor) {
3554 if (anchor == Anchor::Start) return bbox.y1;
3555 if (anchor == Anchor::Center) return bbox_center_y(bbox);
3556 if (anchor == Anchor::End) return bbox.y2;
3557 throw std::invalid_argument("rotate_about_bbox requires a valid y anchor");
3558 }
3559 }
3560
3561 inline Element::BoundingBox Element::include_stroke_width(const BoundingBox& bbox) const {
3562 if (!detail::bbox_is_measured(bbox)) return bbox;
3563 const auto outset = detail::visible_stroke_width(*this) / 2;
3564 return { bbox.x1 - outset, bbox.x2 + outset, bbox.y1 - outset, bbox.y2 + outset };
3565 }
3566
3567 inline TransformList& TransformList::rotate_about_bbox(double degrees,
3568 Anchor x_anchor,
3569 Anchor y_anchor) {
3570 validate_appendable();
3571 if (!owner_) {
3572 throw std::logic_error("rotate_about_bbox requires an owning element transform list");
3573 }
3574 const auto bbox = owner_->layout_bbox();
3575 if (!detail::bbox_is_measured(bbox)) {
3576 throw std::logic_error("rotate_about_bbox requires measured layout bounds");
3577 }
3578 return rotate(degrees,
3579 detail::bbox_anchor_x(bbox, x_anchor),
3580 detail::bbox_anchor_y(bbox, y_anchor));
3581 }
3582
3584 const auto href = this->get_attr("href", this->get_attr("xlink:href"));
3585 if (href.empty() || href[0] != '#') return { NAN, NAN, NAN, NAN };
3586
3587 const auto* root = this->owner_svg();
3588 if (!root) return { NAN, NAN, NAN, NAN };
3589
3590 const auto* referenced = root->get_element_by_id(href.substr(1));
3591 if (!referenced || referenced == this) return { NAN, NAN, NAN, NAN };
3592
3593 Element::BoundingBox bbox = referenced->layout_bbox();
3594 if (!detail::bbox_is_measured(bbox)) return bbox;
3595
3596 const auto x = this->get_attr<double>("x", 0);
3597 const auto y = this->get_attr<double>("y", 0);
3598 const auto width = this->get_attr<double>("width", NAN);
3599 const auto height = this->get_attr<double>("height", NAN);
3600 const auto viewbox = detail::parse_transform_args(referenced->get_attr("viewBox"));
3601 if (!std::isnan(width) && !std::isnan(height) && viewbox.size() == 4 &&
3602 viewbox[2] != 0 && viewbox[3] != 0) {
3603 const auto sx = width / viewbox[2];
3604 const auto sy = height / viewbox[3];
3605 bbox = {
3606 x + (bbox.x1 - viewbox[0]) * sx,
3607 x + (bbox.x2 - viewbox[0]) * sx,
3608 y + (bbox.y1 - viewbox[1]) * sy,
3609 y + (bbox.y2 - viewbox[1]) * sy
3610 };
3611 return include_stroke_width(bbox);
3612 }
3613
3614 bbox = { bbox.x1 + x, bbox.x2 + x, bbox.y1 + y, bbox.y2 + y };
3615 return include_stroke_width(bbox);
3616 }
3617
3619 const double x = this->get_attr<double>("x", 0);
3620 const double y = this->get_attr<double>("y", 0);
3621 const double width = this->get_attr<double>("width", NAN);
3622 const double height = this->get_attr<double>("height", NAN);
3623
3624 if (!std::isnan(width) && !std::isnan(height)) {
3625 return { x, x + width, y, y + height };
3626 }
3627
3628 Element::BoundingBox bbox(NAN, NAN, NAN, NAN);
3629 this->Element::get_bbox(bbox);
3630 if (!detail::bbox_is_measured(bbox)) return bbox;
3631 return { bbox.x1 + x, bbox.x2 + x, bbox.y1 + y, bbox.y2 + y };
3632 }
3633
3634 inline Element& Element::snap_to(const Element& target,
3635 RelativeAlignment relative,
3636 Point offset) {
3637 return snap_to(target, static_cast<Alignment>(relative), offset);
3638 }
3639
3640 inline Element& Element::snap_to(const Element& target,
3641 Alignment alignment,
3642 Point offset) {
3643 const Alignment relative_mask =
3644 static_cast<Alignment>(RelativeAlignment::Left) |
3645 static_cast<Alignment>(RelativeAlignment::Top) |
3646 static_cast<Alignment>(RelativeAlignment::Right) |
3647 static_cast<Alignment>(RelativeAlignment::Bottom);
3648 const Alignment anchor_mask =
3649 static_cast<Alignment>(Anchor::Start) |
3650 static_cast<Alignment>(Anchor::Center) |
3651 static_cast<Alignment>(Anchor::End);
3652
3653 const Alignment relative = alignment & relative_mask;
3654 Alignment anchor = alignment & anchor_mask;
3655 if (detail::alignment_count_bits(relative) != 1) {
3656 throw std::invalid_argument("snap_to requires exactly one relative alignment");
3657 }
3658 if (anchor == 0) {
3659 anchor = static_cast<Alignment>(Anchor::Center);
3660 } else if (detail::alignment_count_bits(anchor) != 1) {
3661 throw std::invalid_argument("snap_to requires at most one anchor");
3662 }
3663 if ((alignment & ~(relative_mask | anchor_mask)) != 0) {
3664 throw std::invalid_argument("snap_to received unknown alignment bits");
3665 }
3666
3667 const auto source_box = this->layout_bbox();
3668 const auto target_box = target.layout_bbox();
3669 if (!detail::bbox_is_measured(source_box) || !detail::bbox_is_measured(target_box)) {
3670 throw std::logic_error("snap_to requires measured layout bounds");
3671 }
3672
3673 double dx = 0;
3674 double dy = 0;
3675 if (relative == static_cast<Alignment>(RelativeAlignment::Left)) {
3676 dx = target_box.x1 - source_box.x2;
3677 } else if (relative == static_cast<Alignment>(RelativeAlignment::Right)) {
3678 dx = target_box.x2 - source_box.x1;
3679 } else if (relative == static_cast<Alignment>(RelativeAlignment::Top)) {
3680 dy = target_box.y1 - source_box.y2;
3681 } else if (relative == static_cast<Alignment>(RelativeAlignment::Bottom)) {
3682 dy = target_box.y2 - source_box.y1;
3683 }
3684
3685 if (relative == static_cast<Alignment>(RelativeAlignment::Left) ||
3686 relative == static_cast<Alignment>(RelativeAlignment::Right)) {
3687 if (anchor == static_cast<Alignment>(Anchor::Start)) {
3688 dy = target_box.y1 - source_box.y1;
3689 } else if (anchor == static_cast<Alignment>(Anchor::Center)) {
3690 dy = detail::bbox_center_y(target_box) - detail::bbox_center_y(source_box);
3691 } else {
3692 dy = target_box.y2 - source_box.y2;
3693 }
3694 } else {
3695 if (anchor == static_cast<Alignment>(Anchor::Start)) {
3696 dx = target_box.x1 - source_box.x1;
3697 } else if (anchor == static_cast<Alignment>(Anchor::Center)) {
3698 dx = detail::bbox_center_x(target_box) - detail::bbox_center_x(source_box);
3699 } else {
3700 dx = target_box.x2 - source_box.x2;
3701 }
3702 }
3703
3704 this->transform().translate(dx + offset.first, dy + offset.second);
3705 return *this;
3706 }
3707
3708 inline Element& Element::align_to(const Element& target,
3709 Axis axis,
3710 Point offset) {
3711 return align_to(target, axis, Anchor::Center, offset);
3712 }
3713
3714 inline Element& Element::align_to(const Element& target,
3715 Axis axis,
3716 Anchor anchor,
3717 Point offset) {
3718 if (axis != Axis::X && axis != Axis::Y) {
3719 throw std::invalid_argument("align_to requires a valid axis");
3720 }
3721 if (anchor != Anchor::Start && anchor != Anchor::Center && anchor != Anchor::End) {
3722 throw std::invalid_argument("align_to requires a valid anchor");
3723 }
3724
3725 const auto source_box = this->layout_bbox();
3726 const auto target_box = target.layout_bbox();
3727 if (!detail::bbox_is_measured(source_box) || !detail::bbox_is_measured(target_box)) {
3728 throw std::logic_error("align_to requires measured layout bounds");
3729 }
3730
3731 double dx = offset.first;
3732 double dy = offset.second;
3733 if (axis == Axis::X) {
3734 if (anchor == Anchor::Start) {
3735 dx += target_box.x1 - source_box.x1;
3736 } else if (anchor == Anchor::Center) {
3737 dx += detail::bbox_center_x(target_box) - detail::bbox_center_x(source_box);
3738 } else {
3739 dx += target_box.x2 - source_box.x2;
3740 }
3741 } else {
3742 if (anchor == Anchor::Start) {
3743 dy += target_box.y1 - source_box.y1;
3744 } else if (anchor == Anchor::Center) {
3745 dy += detail::bbox_center_y(target_box) - detail::bbox_center_y(source_box);
3746 } else {
3747 dy += target_box.y2 - source_box.y2;
3748 }
3749 }
3750
3751 this->transform().translate(dx, dy);
3752 return *this;
3753 }
3754
3755 inline void Element::autoscale_nested_svgs(const AutoscaleOptions& options, bool responsive) {
3756 for (auto& child : this->children) {
3757 if (child->kind() == SVG::static_kind) {
3758 auto* svg_child = static_cast<SVG*>(child.get());
3759 if (responsive) {
3760 svg_child->responsive_autoscale(options);
3761 } else {
3762 svg_child->autoscale(options);
3763 }
3764 } else {
3765 child->autoscale_nested_svgs(options, responsive);
3766 }
3767 }
3768 }
3769
3770 inline Element::BoundingBox Element::get_autoscale_bbox() const {
3771 Element::BoundingBox bbox =
3772 this->kind() == SVG::static_kind && !this->has_layout_bbox()
3773 ? Element::BoundingBox(NAN, NAN, NAN, NAN)
3774 : this->measured_layout_bbox();
3775 this->get_bbox(bbox); // Compute the transform-aware descendant bounds
3776 return bbox;
3777 }
3778
3779 inline void Element::set_viewbox_from_bbox(const BoundingBox& bbox, const Margins& margins) {
3780 double width = bbox.x2 - bbox.x1,
3781 height = bbox.y2 - bbox.y1;
3782
3783 width += margins.x1 + margins.x2;
3784 height += margins.y1 + margins.y2;
3785 double x1 = bbox.x1 - margins.x1,
3786 y1 = bbox.y1 - margins.y1;
3787
3788 std::stringstream viewbox;
3789 viewbox << std::fixed << std::setprecision(1)
3790 << x1 << " " // min-x
3791 << y1 << " " // min-y
3792 << width << " "
3793 << height;
3794 this->set_attr("viewBox", viewbox.str());
3795 }
3796
3797 inline void Element::autoscale(const double margin) {
3799 AutoscaleOptions nested_options(NO_MARGINS);
3800 this->autoscale_nested_svgs(nested_options, false);
3801 auto bbox = this->get_autoscale_bbox();
3802 double width = bbox.x2 - bbox.x1,
3803 height = bbox.y2 - bbox.y1;
3804
3805 AutoscaleOptions options({
3806 width * margin, width * margin,
3807 height * margin, height * margin
3808 }, false);
3809 this->autoscale(options);
3810 }
3811
3812 inline void Element::autoscale(const Margins& margins) {
3813 this->autoscale(AutoscaleOptions(margins));
3814 }
3815
3816 inline void Element::autoscale(const AutoscaleOptions& options) {
3822 if (options.autoscale_nested_svgs) {
3823 this->autoscale_nested_svgs(options, false);
3824 }
3825 auto bbox = this->get_autoscale_bbox();
3826 double width = bbox.x2 - bbox.x1 + options.margins.x1 + options.margins.x2,
3827 height = bbox.y2 - bbox.y1 + options.margins.y1 + options.margins.y2;
3828
3829 this->set_attr("width", width)
3830 .set_attr("height", height);
3831
3832 this->set_viewbox_from_bbox(bbox, options.margins);
3833 }
3834
3835 inline void Element::responsive_autoscale(const double margin) {
3836 AutoscaleOptions nested_options(NO_MARGINS);
3837 this->autoscale_nested_svgs(nested_options, true);
3838 auto bbox = this->get_autoscale_bbox();
3839 double width = bbox.x2 - bbox.x1,
3840 height = bbox.y2 - bbox.y1;
3841
3843 width * margin, width * margin,
3844 height * margin, height * margin
3845 }, false));
3846 }
3847
3848 inline void Element::responsive_autoscale(const Margins& margins) {
3849 this->responsive_autoscale(AutoscaleOptions(margins));
3850 }
3851
3853 if (options.autoscale_nested_svgs) {
3854 this->autoscale_nested_svgs(options, true);
3855 }
3856 this->set_viewbox_from_bbox(this->get_autoscale_bbox(), options.margins);
3857 }
3858
3859 inline void Element::get_bbox(Element::BoundingBox& box, bool visible_only) const {
3861 auto elements = this->descendants(TraversalOptions(false));
3862 for (auto element = elements.begin(); element != elements.end(); ++element) {
3863 const auto* current = *element;
3864 if (visible_only && !detail::renders_in_place(current)) {
3865 continue;
3866 }
3867 auto current_box = current->measured_layout_bbox();
3868 if (!detail::bbox_is_measured(current_box)) {
3869 continue;
3870 }
3871
3872 const auto& transform = element.transform();
3873 const auto p1 = transform.apply({ current_box.x1, current_box.y1 });
3874 const auto p2 = transform.apply({ current_box.x2, current_box.y1 });
3875 const auto p3 = transform.apply({ current_box.x2, current_box.y2 });
3876 const auto p4 = transform.apply({ current_box.x1, current_box.y2 });
3877 Element::BoundingBox transformed_box(
3878 std::min(std::min(p1.first, p2.first), std::min(p3.first, p4.first)),
3879 std::max(std::max(p1.first, p2.first), std::max(p3.first, p4.first)),
3880 std::min(std::min(p1.second, p2.second), std::min(p3.second, p4.second)),
3881 std::max(std::max(p1.second, p2.second), std::max(p3.second, p4.second)));
3882 box = transformed_box + box;
3883 }
3884 }
3885
3886 inline Element::ChildMap Element::get_children() {
3888 Element::ChildMap child_map;
3889 for (auto* child : this->descendants())
3890 child_map[child->tag()].push_back(child);
3891 return child_map;
3892 }
3893
3894 inline Element::ConstChildMap Element::get_children() const {
3896 Element::ConstChildMap child_map;
3897 for (const auto* child : this->descendants())
3898 child_map[child->tag()].push_back(child);
3899 return child_map;
3900 }
3901
3902 inline std::vector<Element*> Element::get_children_helper() {
3904 std::vector<Element*> ret;
3905 for (auto* child : this->descendants()) ret.push_back(child);
3906
3907 return ret;
3908 };
3909
3910 inline std::vector<const Element*> Element::get_children_helper() const {
3912 std::vector<const Element*> ret;
3913 for (const auto* child : this->descendants()) ret.push_back(child);
3914
3915 return ret;
3916 };
3917
3918 inline SVG merge(SVG& left, SVG& right, const Margins& margins) {
3920 SVG ret;
3921
3922 // Move items
3923 ret << std::move(left) << std::move(right);
3924
3925 // Set bounding box of individual pieces
3926 for (auto& svg_child: ret.get_immediate_children<SVG>())
3927 svg_child->autoscale(margins);
3928
3929 // Set x position for child SVG elements, and compute width/height for this
3930 double x = 0, height = 0;
3931 for (auto& svg_child: ret.get_immediate_children<SVG>()) {
3932 svg_child->set_attr("x", x).set_attr("y", 0);
3933 x += svg_child->width();
3934 height = std::max(height, svg_child->height());
3935 }
3936
3937 ret.set_attr("width", x).set_attr("height", height);
3938 return ret;
3939 }
3940
3941 inline std::vector<Point> bounding_polygon(std::vector<Shape*>& shapes) {
3942 /* Convert shapes into sets of points, aggregate them, and then calculate
3943 * convex hull for aggregate set
3944 */
3945 std::vector<Point> points;
3946 for (auto& shp : shapes) {
3947 auto temp_points = shp->points();
3948 std::move(temp_points.begin(), temp_points.end(), std::back_inserter(points));
3949 }
3950
3951 return util::convex_hull(points);
3952 }
3953
3954 inline SVG merge(std::vector<SVG>& frames, const double width, const int max_frame_width) {
3958 SVG root;
3959 double x = 0, y = 0, total_width = 0, total_height = 0;
3960 for (auto& frame : frames) {
3961 // Scale
3962 frame.autoscale();
3963 if (frame.width() > max_frame_width) {
3964 const double scale_factor = max_frame_width/frame.width();
3965 frame.set_attr("width", max_frame_width);
3966 frame.set_attr("height", frame.height() * scale_factor); // Scale height proportionally
3967 }
3968 }
3969
3970 // Move
3971 double current_height = 0;
3972 for (auto& frame : frames) {
3973 // Push to next row
3974 if ((x + frame.width()) > width) {
3975 total_width = std::max(total_width, x);
3976 x = 0;
3977 y += current_height;
3978 current_height = 0;
3979 }
3980
3981 frame.set_attr("x", x).set_attr("y", y);
3982 x += frame.width();
3983 current_height = std::max(current_height, frame.height());
3984 root << std::move(frame);
3985 }
3986
3987 total_height = y + current_height;
3988
3989 // Set viewbox
3990 root.set_attr("viewBox") << 0 << " " << 0 << " " << total_width << " " << total_height;
3991 root.set_attr("width", total_width).set_attr("height", total_height);
3992 return root;
3993 }
3994
3995 inline SVG frame_animate(std::vector<SVG>& frames, const double fps) {
3997 SVG root;
3998 const double duration = (double)frames.size() / fps; // [seconds]
3999 const double frame_step = 1.0 / fps; // duration of each frame [seconds]
4000 int current_frame = 0;
4001
4002 root.style("svg.animated").set_attr("animation-iteration-count", "infinite")
4003 .set_attr("animation-timing-function", "step-end")
4004 .set_attr("animation-duration", std::to_string(duration) + "s")
4005 .set_attr("opacity", 0);
4006
4007 // Move frames into new SVG
4008 for (auto& frame : frames) {
4009 std::string frame_id = "frame_" + std::to_string(current_frame);
4010 frame.set_attr("id", frame_id).set_attr("class", "animated");
4011 root.style("#" + frame_id).set_attr("animation-name",
4012 "anim_" + std::to_string(current_frame));
4013 current_frame++;
4014 root << std::move(frame);
4015 }
4016
4017 // Set animation frames
4018 for (size_t i = 0, ilen = frames.size(); i < ilen; i++) {
4019 auto& anim = root.keyframes("anim_" + std::to_string(i));
4020 double begin_pct = (double)i / frames.size(),
4021 end_pct = (double)(i + 1) / frames.size();
4022 anim["0%"].set_attr("opacity", 0);
4023 anim[std::to_string(begin_pct * 100) + "%"].set_attr("opacity", 1);
4024 anim[std::to_string(end_pct * 100) + "%"].set_attr("opacity", 0);
4025 }
4026
4027 // Scale and center child SVGs
4028 double width = 0, height = 0;
4029
4030 for (auto& child : root.get_immediate_children<SVG>()) {
4031 child->autoscale();
4032 width = std::max(width, child->width());
4033 height = std::max(height, child->height());
4034 }
4035
4036 root.set_attr("viewBox", "0 0 " + std::to_string(width) + " " + std::to_string(height));
4037
4038 // Center child SVGs
4039 for (auto& child : root.get_immediate_children<SVG>())
4040 child->set_attr("x", (width - child->width())/2).set_attr("y", (height - child->height())/2);
4041
4042 return root;
4043 }
4044}
Base class for anything that has attributes (e.g. SVG elements, CSS stylesheets).
Definition svg.hpp:1198
AttributeMap & set_attrs(const SVGAttrib &values)
Definition svg.hpp:1285
AttributeMap & set_attrs(std::initializer_list< std::pair< std::string, std::string > > values)
Definition svg.hpp:1276
std::enable_if< detail::is_numeric_attr_type< T >::value, T >::type get_attr(const std::string &key, T fallback) const
Definition svg.hpp:1260
Definition svg.hpp:3183
ElementKind kind() const override
Definition svg.hpp:3188
Ordered token list for managing the class attribute.
Definition svg.hpp:803
bool toggle(const std::string &token)
Definition svg.hpp:840
ClassList & remove(const std::string &token)
Definition svg.hpp:828
std::string str() const
Definition svg.hpp:863
std::vector< std::string > tokens() const
Definition svg.hpp:868
ClassList & set(const std::string &class_names)
Definition svg.hpp:851
bool contains(const std::string &token) const
Definition svg.hpp:810
ClassList & clear()
Definition svg.hpp:857
ClassList & add(const std::string &token)
Definition svg.hpp:817
std::string classes(Keys... keys) const
Definition svg.hpp:1595
Classes(std::initializer_list< ClassSpec< T > > specs)
Definition svg.hpp:1576
std::string selector(Keys... keys) const
Definition svg.hpp:1584
Definition svg.hpp:181
Color mix(const Color &other, double amount) const
Definition svg.hpp:260
Color tint(double amount) const
Definition svg.hpp:268
static Color hsl(double hue, double saturation, double lightness)
Definition svg.hpp:216
static Color rgb(int red, int green, int blue)
Definition svg.hpp:184
static Color hex(std::string value)
Definition svg.hpp:189
static Color black()
Definition svg.hpp:283
static Color white()
Definition svg.hpp:278
Color shade(double amount) const
Definition svg.hpp:273
Definition svg.hpp:2357
RadialGradient & radial_gradient(std::string id)
Definition svg.hpp:2977
LinearGradient & linear_gradient(std::string id)
Definition svg.hpp:2970
ElementKind kind() const override
Definition svg.hpp:2361
Symbol * symbol(std::string id)
Definition svg.hpp:2984
Represents the top left and bottom right corners of a bounding rectangle.
Definition svg.hpp:1635
Definition svg.hpp:2248
Definition svg.hpp:2040
Definition svg.hpp:2234
Abstract base class for all SVG elements.
Definition svg.hpp:1630
std::vector< T * > get_immediate_children()
Definition svg.hpp:1757
Element & snap_to(const Element &target, RelativeAlignment relative, Point offset=Point(0, 0))
Definition svg.hpp:3634
std::vector< Element * > get_children_helper()
Definition svg.hpp:3902
DepthFirstRange depth_first()
Definition svg.hpp:2264
Element & operator<<(T &&node)
Definition svg.hpp:1722
virtual std::string tag() const
Definition svg.hpp:1884
virtual std::string tag()
Definition svg.hpp:1882
std::vector< const T * > get_children() const
Definition svg.hpp:1744
bool has_layout_bbox() const
Definition svg.hpp:1808
Element * get_element_by_id(const std::string &id)
Definition svg.hpp:1973
T * add_child(Args &&... args)
Definition svg.hpp:1714
Element & layout_bbox(const BoundingBox &bbox)
Definition svg.hpp:3451
Element & align_to(const Element &target, Axis axis, Point offset=Point(0, 0))
Definition svg.hpp:3708
Element & clear_layout_bbox()
Definition svg.hpp:3466
std::vector< const T * > get_immediate_children() const
Definition svg.hpp:1769
std::vector< T * > get_children()
Definition svg.hpp:1731
void responsive_autoscale(const Margins &margins=DEFAULT_MARGINS)
Definition svg.hpp:3848
virtual ElementKind kind() const
Definition svg.hpp:1786
DepthFirstIterator begin()
Definition svg.hpp:2280
virtual BoundingBox get_bbox() const
Definition svg.hpp:2312
BoundingBox layout_bbox() const
Definition svg.hpp:3472
std::vector< Element * > get_elements_by_class(const std::string &clsname)
Definition svg.hpp:1991
double find_numeric(const std::string &key) const
Definition svg.hpp:1935
Element & bbox_padding(const Margins &padding)
Definition svg.hpp:3457
std::unique_ptr< Element > clone_element() const
Definition svg.hpp:2019
std::vector< std::unique_ptr< Element > >::iterator ChildIterator
Definition svg.hpp:1870
DepthFirstRange descendants()
Definition svg.hpp:2296
Definition svg.hpp:3112
ElementKind kind() const override
Definition svg.hpp:3116
Definition svg.hpp:3125
std::pair< double, double > along(double percent) const
Definition svg.hpp:3290
ElementKind kind() const override
Definition svg.hpp:3130
Definition svg.hpp:2455
Definition svg.hpp:3013
void line_to(T x, T y)
Definition svg.hpp:3030
void start(T x, T y)
Definition svg.hpp:3020
void to_origin()
Definition svg.hpp:3047
ElementKind kind() const override
Definition svg.hpp:3017
Definition svg.hpp:3210
ElementKind kind() const override
Definition svg.hpp:3215
Definition svg.hpp:2510
Definition svg.hpp:3161
ElementKind kind() const override
Definition svg.hpp:3166
Definition svg.hpp:2632
SelectorProperties css
Definition svg.hpp:2637
std::map< std::string, SelectorProperties > media_queries
Definition svg.hpp:2638
std::string svg_to_string(const size_t) const override
Definition svg.hpp:3407
ElementKind kind() const override
Definition svg.hpp:2640
std::map< std::string, SelectorProperties > keyframes
Definition svg.hpp:2639
Definition svg.hpp:2625
AttributeMap & media_style(const std::string &query, const std::string &key)
Definition svg.hpp:2704
SVG(const SVG &other)
Definition svg.hpp:2657
AttributeMap & style(const std::string &key)
Definition svg.hpp:2695
const T * get_element_by_id(const std::string &id) const
Definition svg.hpp:2785
SVG(SVGAttrib _attr={ { "xmlns", "http://www.w3.org/2000/svg" } })
Definition svg.hpp:2649
SVG clone() const
Definition svg.hpp:2690
T * get_element_by_id(const std::string &id)
Definition svg.hpp:2776
ElementKind kind() const override
Definition svg.hpp:2793
Variables< T > set_vars(std::initializer_list< VariableSpec< T > > specs)
Definition svg.hpp:2716
BoundingBox get_bbox() const override
Definition svg.hpp:3618
std::map< std::string, AttributeMap > & keyframes(const std::string &key)
Definition svg.hpp:2734
Defs * defs()
Definition svg.hpp:2744
Variables< T > set_vars(const std::string &selector, std::initializer_list< VariableSpec< T > > specs)
Definition svg.hpp:2722
Variables< T > set_vars(const std::string &query, const std::string &selector, std::initializer_list< VariableSpec< T > > specs)
Definition svg.hpp:2728
SVG & media_style(const std::string &query, const std::string &key, const Attrs &attrs)
Definition svg.hpp:2709
SVG & style(const std::string &key, const Attrs &attrs)
Definition svg.hpp:2698
Style * css
Definition svg.hpp:2792
Base class for any SVG elements that have a width and height.
Definition svg.hpp:2320
virtual std::vector< Point > points() const
Definition svg.hpp:2329
virtual double height() const
Definition svg.hpp:2348
virtual double width() const
Definition svg.hpp:2342
Definition svg.hpp:2566
Element::BoundingBox get_bbox() const override
Definition svg.hpp:2999
ElementKind kind() const override
Definition svg.hpp:2578
std::string href() const
Definition svg.hpp:2991
Use use(double x, double y) const
Definition svg.hpp:3005
Definition svg.hpp:3063
ElementKind kind() const override
Definition svg.hpp:3068
BoundingBox get_bbox() const override
Definition svg.hpp:3229
Definition svg.hpp:3091
std::string svg_to_string(const size_t) const override
Definition svg.hpp:3447
Title(const char *_content)
Definition svg.hpp:3097
ElementKind kind() const override
Definition svg.hpp:3100
static constexpr ElementKind static_kind
Definition svg.hpp:3094
std::string content
Definition svg.hpp:3104
Title(std::string _content)
Definition svg.hpp:3099
Ordered function list for managing the transform attribute.
Definition svg.hpp:938
TransformList & rotate_about_bbox(double degrees, Anchor x_anchor, Anchor y_anchor)
Definition svg.hpp:3567
TransformList & append(const std::string &transform)
Definition svg.hpp:947
TransformList & clear()
Definition svg.hpp:968
TransformList & set(const std::string &transform)
Definition svg.hpp:962
std::string str() const
Definition svg.hpp:1017
Definition svg.hpp:2591
ElementKind kind() const override
Definition svg.hpp:2617
Element::BoundingBox get_bbox() const override
Definition svg.hpp:3583
Use & xlink_href(std::string href)
Definition svg.hpp:2613
Definition svg.hpp:1466
std::string var(T key) const
Definition svg.hpp:1487
Variables & set(T key, const std::string &value)
Definition svg.hpp:1492
Variables(AttributeMap &target, std::initializer_list< VariableSpec< T > > specs)
Definition svg.hpp:1469
Variables & set(T key, const char *value)
Definition svg.hpp:1498
std::string format(const std::string &pattern, Keys... keys) const
Definition svg.hpp:1504
Main namespace for SVG for C++.
Definition svg.hpp:60
SVG frame_animate(std::vector< SVG > &frames, const double fps)
Definition svg.hpp:3995
std::string tag_name(ElementKind kind)
Definition svg.hpp:95
std::map< std::string, AttributeMap > SelectorProperties
Definition svg.hpp:126
Group G
Definition svg.hpp:3123
std::string escape_xml(const std::string &text)
Definition svg.hpp:1189
SVG merge(SVG &left, SVG &right, const Margins &margins=DEFAULT_MARGINS)
Definition svg.hpp:3918
RelativeAlignment
Definition svg.hpp:149
unsigned Alignment
Definition svg.hpp:170
ElementKind
Definition svg.hpp:74
Anchor
Definition svg.hpp:157
Axis
Definition svg.hpp:164
std::string to_string(const double &value)
Definition svg.hpp:1150
Various utility and mathematical functions.
Definition svg.hpp:1200
AttrSetter & operator<<(const Color &value)
Definition svg.hpp:1207
Definition svg.hpp:129
Definition svg.hpp:137
bool autoscale_nested_svgs
Definition svg.hpp:145
Definition svg.hpp:1453
ClassSpec(T _key, std::string _css_class)
Definition svg.hpp:1460
T key
Definition svg.hpp:1455
std::string css_class
Definition svg.hpp:1457
Definition svg.hpp:1660
bool descend_into_nested_svgs
Definition svg.hpp:1665
Definition svg.hpp:118
Definition svg.hpp:1429
VariableSpec(T _key, std::string _css_name, std::string _value)
Definition svg.hpp:1444
T key
Definition svg.hpp:1431
std::string css_name
Definition svg.hpp:1433
std::string value
Definition svg.hpp:1437
bool has_value
Definition svg.hpp:1435
VariableSpec(T _key, std::string _css_name)
Definition svg.hpp:1440
T min_or_not_nan(T first, T second)
Definition svg.hpp:1062
std::vector< Point > polar_points(int n, int a, int b, double radius)
Definition svg.hpp:1131
T max_or_not_nan(T first, T second)
Definition svg.hpp:1075
std::vector< Point > convex_hull(std::vector< Point > &points)
Definition svg.hpp:1096
std::string text_content_element_to_string(const Element &element, const std::string &tag, const std::string &content, const size_t indent_level)
Definition svg.hpp:3338