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 "";
127 using SVGAttrib = std::map<std::string, std::string>;
130 using SVGAttrib::SVGAttrib;
132 using Point = std::pair<double, double>;
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) :
177 return relative | anchor;
184 static Color
rgb(
int red,
int green,
int blue) {
185 return Color(channel(red), channel(green), channel(blue));
189 static Color
hex(std::string value) {
190 if (!value.empty() && value[0] ==
'#') {
191 value.erase(value.begin());
193 if (value.size() != 3 && value.size() != 6) {
194 throw std::invalid_argument(
"Hex colors must use 3 or 6 digits");
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");
201 ch =
static_cast<char>(std::tolower(
static_cast<unsigned char>(ch)));
204 if (value.size() == 3) {
205 value = std::string{ value[0], value[0],
207 value[2], value[2] };
210 return Color(from_hex_pair(value, 0),
211 from_hex_pair(value, 2),
212 from_hex_pair(value, 4));
216 static Color
hsl(
double hue,
double saturation,
double lightness) {
217 validate_percentage(saturation,
"Saturation");
218 validate_percentage(lightness,
"Lightness");
220 hue = std::fmod(hue, 360.0);
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;
237 }
else if (hue < 120) {
240 }
else if (hue < 180) {
243 }
else if (hue < 240) {
246 }
else if (hue < 300) {
254 return Color(channel_from_unit(red + m),
255 channel_from_unit(green + m),
256 channel_from_unit(blue + m));
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));
268 Color
tint(
double amount)
const {
279 return rgb(255, 255, 255);
288 operator std::string()
const {
293 Color(uint8_t red, uint8_t green, uint8_t blue) : red_(red), green_(green), blue_(blue) {}
295 std::string serialize()
const {
296 std::ostringstream 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_);
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");
309 return static_cast<uint8_t
>(value);
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)));
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));
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)));
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");
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");
342#if __cplusplus < 201402L
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)...));
351 using std::make_unique;
357 template<
size_t... I>
358 struct index_sequence {};
360 template<
size_t N,
size_t... I>
361 struct make_index_sequence : make_index_sequence<N - 1, N - 1, I...> {};
363 template<
size_t... I>
364 struct make_index_sequence<0, I...> {
365 using type = index_sequence<I...>;
369 struct is_attrs : std::is_same<typename std::decay<T>::type, Attrs> {};
371 template<
typename... Args>
372 struct last_is_attrs : std::false_type {};
375 struct last_is_attrs<T> : is_attrs<T> {};
377 template<
typename T,
typename... Rest>
378 struct last_is_attrs<T, Rest...> : last_is_attrs<Rest...> {};
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);
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)...);
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>(
400 typename make_index_sequence<
sizeof...(Args) - 1>::type{});
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)...);
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_) {}
420 Point apply(Point point)
const {
422 a * point.first + c * point.second + e,
423 b * point.first + d * point.second + f
428 inline AffineTransform multiply(
const AffineTransform& left,
const AffineTransform& right) {
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
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);
448 cx - cos_value * cx + sin_value * cy,
449 cy - sin_value * cx - cos_value * cy
453 inline AffineTransform translate_transform(
double x,
double y = 0) {
454 return { 1, 0, 0, 1, x, y };
457 inline double parse_number_or(
const std::string& value,
double fallback) {
458 if (value.empty())
return fallback;
460 return std::stof(value);
461 }
catch (
const std::invalid_argument&) {
463 }
catch (
const std::out_of_range&) {
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;
478 inline std::vector<double> parse_transform_args(std::string args) {
479 for (
auto& ch : args) {
485 std::istringstream stream(args);
486 std::vector<double> values;
488 while (stream >> value) {
489 values.push_back(value);
494 class TextEstimator {
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_)) {}
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;
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;
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);
532 previous_was_joiner =
false;
533 regional_pair_open =
false;
536 if (codepoint ==
'\n') {
537 longest = std::max(longest, current);
540 previous_was_joiner =
false;
541 regional_pair_open =
false;
545 current += glyph_advance(codepoint, previous_was_joiner, regional_pair_open);
546 previous_was_joiner = codepoint == 0x200d;
549 longest = std::max(longest, current);
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;
561 std::string font_weight;
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;
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;
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;
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;
594 codepoint = (codepoint << 6) | (next & 0x3f);
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)) {
607 static bool in_range(uint32_t value, uint32_t first, uint32_t last) {
608 return value >= first && value <= last;
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);
632 static bool is_variation_selector(uint32_t codepoint) {
633 return in_range(codepoint, 0xfe00, 0xfe0f) ||
634 in_range(codepoint, 0xe0100, 0xe01ef);
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);
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);
656 static bool is_regional_indicator(uint32_t codepoint) {
657 return in_range(codepoint, 0x1f1e6, 0x1f1ff);
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);
666 static double ascii_advance(uint32_t codepoint) {
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;
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)) {
724 if (previous_was_joiner)
return 0;
726 if (is_regional_indicator(codepoint)) {
727 regional_pair_open = !regional_pair_open;
728 return regional_pair_open ? 1.10 : 0;
730 regional_pair_open =
false;
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;
740 inline AffineTransform parse_supported_transform(
const std::string& transform) {
741 AffineTransform current;
743 while (pos < transform.size()) {
744 while (pos < transform.size() && std::isspace(
static_cast<unsigned char>(transform[pos]))) {
747 const auto name_start = pos;
748 while (pos < transform.size() && std::isalpha(
static_cast<unsigned char>(transform[pos]))) {
751 if (name_start == pos) {
755 const auto name = transform.substr(name_start, pos - name_start);
756 while (pos < transform.size() && std::isspace(
static_cast<unsigned char>(transform[pos]))) {
759 if (pos >= transform.size() || transform[pos] !=
'(') {
762 const auto args_start = ++pos;
763 const auto args_end = transform.find(
')', args_start);
764 if (args_end == std::string::npos) {
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)) {
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)) {
778 args.size() == 1 ? translate_transform(args[0])
779 : translate_transform(args[0], args[1]));
787 inline std::string
to_string(
const double& value);
788 inline std::string
to_string(
const Point& point);
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);
795 std::vector<Point> bounding_polygon(
const std::vector<Shape*>& shapes);
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);
805 ClassList() =
default;
806 explicit ClassList(std::string& value) : mutable_value_(&value), value_(&value) {}
807 explicit ClassList(
const std::string& value) : value_(&value) {}
811 validate_token(token);
812 const auto values =
tokens();
813 return std::find(values.begin(), values.end(), token) != values.end();
817 ClassList&
add(
const std::string& token) {
818 validate_token(token);
820 if (std::find(values.begin(), values.end(), token) == values.end()) {
821 values.push_back(token);
828 ClassList&
remove(
const std::string& token) {
829 validate_token(token);
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) {
851 ClassList&
set(
const std::string& class_names) {
852 write(parse(class_names));
868 std::vector<std::string>
tokens()
const {
869 return parse(value());
873 static bool is_space(
char ch) {
874 return std::isspace(
static_cast<unsigned char>(ch)) != 0;
877 static void validate_token(
const std::string& token) {
879 throw std::invalid_argument(
"class token cannot be empty");
881 if (std::find_if(token.begin(), token.end(), is_space) != token.end()) {
882 throw std::invalid_argument(
"class token cannot contain whitespace");
886 static std::vector<std::string> parse(
const std::string& class_names) {
887 std::vector<std::string> result;
889 for (
const auto ch : class_names) {
891 if (!token.empty()) {
892 if (std::find(result.begin(), result.end(), token) == result.end()) {
893 result.push_back(token);
901 if (!token.empty() && std::find(result.begin(), result.end(), token) == result.end()) {
902 result.push_back(token);
907 static std::string join(
const std::vector<std::string>& values) {
909 for (std::size_t i = 0; i < values.size(); ++i) {
918 const std::string& value()
const {
919 static const std::string empty;
920 return value_ ? *value_ : empty;
923 void write(
const std::vector<std::string>& values) {
924 if (!mutable_value_) {
925 throw std::logic_error(
"cannot mutate a const class list");
927 *mutable_value_ = join(values);
928 value_ = mutable_value_;
931 std::string* mutable_value_ =
nullptr;
932 const std::string* value_ =
nullptr;
938 class TransformList {
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) {}
947 TransformList&
append(
const std::string& transform) {
948 validate_appendable();
949 if (transform.empty()) {
950 throw std::invalid_argument(
"transform cannot be empty");
953 if (
str().empty() ||
str() ==
"none") {
956 write(
str() +
" " + transform);
962 TransformList&
set(
const std::string& transform) {
973 TransformList& matrix(
double a,
double b,
double c,
double d,
double e,
double f) {
974 std::stringstream ss;
980 TransformList& translate(
double x) {
984 TransformList& translate(
double x,
double y) {
988 TransformList& scale(
double factor) {
992 TransformList& scale(
double x,
double y) {
996 TransformList& rotate(
double degrees) {
1000 TransformList& rotate(
double degrees,
double cx,
double cy) {
1008 TransformList& skew_x(
double degrees) {
1012 TransformList& skew_y(
double degrees) {
1022 static bool is_keyword(
const std::string& transform) {
1023 return transform ==
"inherit" || transform ==
"initial" || transform ==
"revert" ||
1024 transform ==
"revert-layer" || transform ==
"unset";
1027 const std::string& value()
const {
1028 static const std::string empty;
1029 return value_ ? *value_ : empty;
1032 void validate_appendable()
const {
1033 if (is_keyword(value())) {
1034 throw std::logic_error(
"cannot append transform functions to a transform keyword");
1038 void write(
const std::string& value) {
1039 if (!mutable_value_) {
1040 throw std::logic_error(
"cannot mutate a const transform list");
1042 *mutable_value_ = value;
1043 value_ = mutable_value_;
1046 std::string* mutable_value_ =
nullptr;
1047 const std::string* value_ =
nullptr;
1048 const Element* owner_ =
nullptr;
1056 COLINEAR, CLOCKWISE, COUNTERCLOCKWISE
1059 inline std::vector<Point> polar_points(
int n,
int a,
int b,
double radius);
1061 template<
typename T>
1066 if (isnan(first) && isnan(second))
1068 else if (isnan(first) || isnan(second))
1069 return isnan(first) ? second : first;
1071 return std::min(first, second);
1074 template<
typename T>
1079 if (isnan(first) && isnan(second))
1081 else if (isnan(first) || isnan(second))
1082 return isnan(first) ? second : first;
1084 return std::max(first, second);
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));
1091 if (value == 0)
return COLINEAR;
1092 else if (value > 0)
return CLOCKWISE;
1093 else return COUNTERCLOCKWISE;
1103 if (points.size() < 3)
return {};
1104 std::vector<Point> hull;
1108 for (
size_t i = 0; i < points.size(); i++)
1109 if (points[i].first < points[left].first) left = (int)i;
1112 int current = left, next;
1115 hull.push_back(points[current]);
1118 next = (current + 1) % points.size();
1119 for (
size_t i = 0; i < points.size(); i++) {
1121 if (orientation(points[current], points[next], points[i]) == COUNTERCLOCKWISE)
1126 }
while (current != left);
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)),
1142 b + radius * sin(degree * (PI/180))
1152 std::stringstream ss;
1153 ss << std::fixed << std::setprecision(1);
1165 return static_cast<std::string
>(color);
1169 inline void append_escaped_xml(std::string& out,
const std::string& text) {
1171 for (
size_t i = 0; i < text.size(); ++i) {
1174 case '&': entity =
"&";
break;
1175 case '<': entity =
"<";
break;
1176 case '>': entity =
">";
break;
1177 case '"': entity =
""";
break;
1178 case '\'': entity =
"'";
break;
1181 out.append(text, start, i - start);
1185 out.append(text, start, text.size() - start);
1191 detail::append_escaped_xml(out, text);
1198 class AttributeMap {
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) {};
1208 attr_ +=
static_cast<std::string
>(value);
1214 template<
typename T>
1216 attr_ += std::to_string(value);
1224 if (normalize_class_) {
1235 SVGAttrib::mapped_type& attr_;
1236 bool normalize_class_ =
false;
1237 std::function<void(
const std::string&)> on_update_;
1240 AttributeMap() =
default;
1241 virtual ~AttributeMap() =
default;
1242 AttributeMap(SVGAttrib _attr) : attr_(std::move(_attr)) {};
1244 const SVGAttrib& attrs()
const {
1248 bool has_attr(
const std::string& key)
const {
1249 return this->attr_.find(key) != this->attr_.end();
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;
1258 template<
typename T>
1259 typename std::enable_if<detail::is_numeric_attr_type<T>::value, T>::type
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)));
1266 template<
typename T>
1267 AttributeMap& set_attr(
const std::string key, T value) {
1268 this->set_attr_value(key, std::to_string(value));
1273 AttributeMap& set_attr(
const std::string key,
const Color& value);
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);
1286 for (
const auto& pair : values) {
1287 this->set_attr_value(pair.first, pair.second);
1293 AttrSetter set_attr(
const std::string key) {
1294 return this->make_attr_setter(key);
1297 ClassList class_list() {
1298 return ClassList(this->attr_[
"class"]);
1301 ClassList class_list()
const {
1302 const auto found = this->attr_.find(
"class");
1303 return found == this->attr_.end() ? ClassList() : ClassList(found->second);
1306 TransformList transform_list() {
1307 return TransformList(this->attr_[
"transform"]);
1310 TransformList transform_list()
const {
1311 const auto found = this->attr_.find(
"transform");
1312 return found == this->attr_.end() ? TransformList() : TransformList(found->second);
1315 TransformList transform() {
1316 return transform_list();
1319 TransformList transform()
const {
1320 return transform_list();
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);
1329 this->attr_[key] = value;
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");
1337 SVGAttrib& mutable_attrs() {
1362 inline AttributeMap& AttributeMap::set_attr(
const std::string key,
const double value) {
1364 this->set_attr_value(key,
to_string(value));
1368 inline AttributeMap& AttributeMap::set_attr(
const std::string key,
const Color& value) {
1369 this->set_attr_value(key,
static_cast<std::string
>(value));
1374 inline AttributeMap& AttributeMap::set_attr(
const std::string key,
const char * value) {
1376 this->set_attr_value(key, value);
1381 inline AttributeMap& AttributeMap::set_attr(
const std::string key,
const std::string value) {
1383 this->set_attr_value(key, value);
1390 template<
typename T>
1392 static_assert(std::is_enum<T>::value,
"Typed CSS keys must be an enum type.");
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");
1401 return found->second;
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");
1410 if (this->used_names_.find(normalized_name) != this->used_names_.end()) {
1411 throw std::invalid_argument(
"Duplicate " + duplicate_label +
": " + normalized_name);
1414 this->names_[key] = normalized_name;
1415 this->used_names_.insert(normalized_name);
1420 std::map<T, std::string> names_;
1422 std::set<std::string> used_names_;
1428 template<
typename T>
1448 value(std::move(_value)) {}
1452 template<
typename T>
1465 template<
typename T>
1471 std::vector<std::pair<T, std::string>> initial_values;
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 });
1481 for (
const auto& initial : initial_values) {
1482 this->
set(initial.first, initial.second);
1487 std::string
var(T key)
const {
1488 return "var(" + this->name(key) +
")";
1493 this->target_->set_attr(this->name(key), value);
1499 return this->
set(key, std::string(value));
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);
1509 for (
size_t i = 0; i < pattern.size(); ++i) {
1510 if (pattern[i] ==
'{') {
1511 if (i + 1 < pattern.size() && pattern[i + 1] ==
'{') {
1517 const auto start = i + 1;
1520 while (pos < pattern.size() && std::isdigit(
static_cast<unsigned char>(pattern[pos]))) {
1521 index = index * 10 +
static_cast<size_t>(pattern[pos] -
'0');
1524 if (pos == start || pos >= pattern.size() || pattern[pos] !=
'}') {
1525 throw std::invalid_argument(
"Malformed CSS variable format placeholder");
1527 if (index >= args.size()) {
1528 throw std::invalid_argument(
"CSS variable format placeholder index out of range");
1534 }
else if (pattern[i] ==
'}') {
1535 if (i + 1 < pattern.size() && pattern[i + 1] ==
'}') {
1540 throw std::invalid_argument(
"Unmatched CSS variable format brace");
1542 out.push_back(pattern[i]);
1546 for (
const auto was_used : used) {
1548 throw std::invalid_argument(
"Unused CSS variable format argument");
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");
1561 if (css_name.size() >= 2 && css_name[0] ==
'-' && css_name[1] ==
'-') {
1564 return "--" + css_name;
1568 AttributeMap* target_;
1572 template<
typename T>
1577 for (
const auto& spec : specs) {
1578 this->add_name(spec.key, normalize_name(spec.css_class),
"CSS class name");
1583 template<
typename... Keys>
1585 const auto names = this->names(keys...);
1587 for (
const auto& name : names) {
1594 template<
typename... Keys>
1596 const auto names = this->names(keys...);
1598 for (
const auto& name : names) {
1599 if (!out.empty()) out +=
" ";
1606 static std::string normalize_name(std::string css_class) {
1607 if (!css_class.empty() && css_class[0] ==
'.') {
1608 css_class.erase(0, 1);
1610 if (css_class.empty()) {
1611 throw std::invalid_argument(
"CSS class name cannot be empty");
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");
1621 template<
typename... Keys>
1622 std::vector<std::string> names(Keys... keys)
const {
1623 return std::vector<std::string>{ this->name(keys)... };
1630 class Element:
public AttributeMap {
1637 using QuadCoord::QuadCoord;
1638 BoundingBox() =
default;
1639 BoundingBox(
double a,
double b,
double c,
double d) :
QuadCoord({ a, b, c, d }) {};
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);
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) :
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)),
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();
1686 if (
this != &other) {
1687 AttributeMap::operator=(std::move(other));
1688 children = std::move(other.children);
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();
1701 Element(
const char*
id) : AttributeMap(
1702 SVGAttrib({ {
"id",
id } })) {};
1703 using AttributeMap::AttributeMap;
1706 operator std::string()
const {
return this->svg_to_string(0); };
1711 std::unique_ptr<Element> clone_element()
const;
1713 template<
typename T,
typename... Args>
1717 auto child = detail::make_child<T>(std::forward<Args>(args)...);
1718 return this->insert_new_child(std::move(child), this->children.end());
1721 template<
typename T>
1725 auto child = detail::make_unique<T>(std::move(node));
1726 this->insert_new_child(std::move(child), this->children.end());
1730 template<
typename T>
1734 std::vector<T*> ret;
1737 for (
auto& child: child_elems)
1738 if (child->kind() == T::static_kind) ret.push_back(
static_cast<T*
>(child));
1743 template<
typename T>
1747 std::vector<const T*> ret;
1750 for (
auto& child: child_elems)
1751 if (child->kind() == T::static_kind) ret.push_back(
static_cast<const T*
>(child));
1756 template<
typename T>
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()));
1768 template<
typename T>
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()));
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_; }
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);
1794 void responsive_autoscale(
const Margins& margins=DEFAULT_MARGINS);
1796 void responsive_autoscale(
const double margin);
1800 Element& layout_bbox(
const BoundingBox& bbox);
1802 Element& bbox_padding(
const Margins& padding);
1804 Element& bbox_padding(
double padding);
1810 BoundingBox layout_bbox()
const;
1814 Point offset = Point(0, 0));
1818 Point offset = Point(0, 0));
1822 Point offset = Point(0, 0));
1827 Point offset = Point(0, 0));
1829 return TransformList(this->mutable_attrs()[
"transform"],
this);
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);
1836 TransformList transform() {
1837 return transform_list();
1839 TransformList transform()
const {
1840 return transform_list();
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;
1869 std::vector<std::unique_ptr<Element>> children;
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);
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;
1884 virtual std::string
tag()
const {
return const_cast<Element*
>(
this)->
tag(); }
1885 virtual std::unique_ptr<Element> clone_element_impl()
const;
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>();
1896 void set_attr_value(
const std::string& key,
const std::string& value)
override;
1897 AttrSetter make_attr_setter(
const std::string& key)
override;
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();
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));
1913 Element* insert_child(std::unique_ptr<Element> child, ChildIterator position) {
1914 child->parent_ =
this;
1915 child->set_owner_svg(this->owner_svg());
1917 child->register_subtree_ids();
1919 child->unregister_subtree_ids();
1920 child->set_owner_svg(
nullptr);
1921 child->parent_ =
nullptr;
1924 return children.insert(position, std::move(child))->get();
1927 void reparent_children() {
1928 for (
auto& child : children) {
1929 child->parent_ =
this;
1930 child->set_owner_svg(this->owner_);
1931 child->reparent_children();
1940 if (this->has_attr(key))
1941 return std::stof(this->get_attr(key));
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;
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;
1960 Element::ChildList ret;
1961 for (
auto& child : this->children) ret.push_back(child.get());
1968 Element::ConstChildList ret;
1969 for (
auto& child : this->children) ret.push_back(child.get());
1976 for (
auto& current: child_elems)
1977 if (current->id() ==
id)
return current;
1985 for (
auto& current: child_elems)
1986 if (current->id() ==
id)
return current;
1993 std::vector<Element*> ret;
1996 for (
auto& current: child_elems) {
1997 if (current->has_attr(
"class")
1998 && current->class_list().contains(clsname))
1999 ret.push_back(current);
2007 std::vector<const Element*> ret;
2010 for (
auto& current: child_elems) {
2011 if (current->has_attr(
"class")
2012 && current->class_list().contains(clsname))
2013 ret.push_back(current);
2020 return this->clone_element_impl();
2023 inline Element::Element(
const Element& other) :
2024 AttributeMap(other.attrs()),
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());
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.");
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*&;
2048 DepthFirstIterator() =
default;
2053 const auto root_transform = transform_for(root, detail::AffineTransform());
2055 pending_.push_back(Frame(root, root_transform,
true));
2057 push_children(root, root_transform);
2062 Element* operator*()
const {
return current_.element; }
2063 const detail::AffineTransform& transform()
const {
return current_.transform; }
2065 DepthFirstIterator& operator++() {
2070 DepthFirstIterator operator++(
int) {
2076 bool operator==(
const DepthFirstIterator& other)
const {
2077 if (end_ || other.end_)
return end_ == other.end_;
2078 return current_.element == other.current_.element;
2081 bool operator!=(
const DepthFirstIterator& other)
const {
2082 return !(*
this == other);
2087 Frame() : element(
nullptr), transform(), root(
false) {}
2088 Frame(Element* element,
const detail::AffineTransform& transform,
bool root =
false) :
2090 transform(transform),
2094 detail::AffineTransform transform;
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")));
2104 return parent_transform;
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)));
2115 if (pending_.empty()) {
2121 current_ = pending_.back();
2122 pending_.pop_back();
2124 if (current_.root || options_.descend_into_nested_svgs ||
2125 current_.element->kind() != ElementKind::SVG) {
2126 push_children(current_.element, current_.transform);
2130 std::vector<Frame> pending_;
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*&;
2144 ConstDepthFirstIterator() =
default;
2145 ConstDepthFirstIterator(
const Element* root,
2151 const auto root_transform = transform_for(root, detail::AffineTransform());
2153 pending_.push_back(Frame(root, root_transform,
true));
2155 push_children(root, root_transform);
2160 const Element* operator*()
const {
return current_.element; }
2161 const detail::AffineTransform& transform()
const {
return current_.transform; }
2163 ConstDepthFirstIterator& operator++() {
2168 ConstDepthFirstIterator operator++(
int) {
2174 bool operator==(
const ConstDepthFirstIterator& other)
const {
2175 if (end_ || other.end_)
return end_ == other.end_;
2176 return current_.element == other.current_.element;
2179 bool operator!=(
const ConstDepthFirstIterator& other)
const {
2180 return !(*
this == other);
2185 Frame() : element(
nullptr), transform(), root(
false) {}
2186 Frame(
const Element* element,
const detail::AffineTransform& transform,
bool root =
false) :
2188 transform(transform),
2191 const Element* element;
2192 detail::AffineTransform transform;
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")));
2202 return parent_transform;
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)));
2213 if (pending_.empty()) {
2219 current_ = pending_.back();
2220 pending_.pop_back();
2222 if (current_.root || options_.descend_into_nested_svgs ||
2223 current_.element->kind() != ElementKind::SVG) {
2224 push_children(current_.element, current_.transform);
2228 std::vector<Frame> pending_;
2237 root_(root), include_root_(include_root), options_(options) {}
2250 ConstDepthFirstRange(
const Element* root,
2253 root_(root), include_root_(include_root), options_(options) {}
2259 const Element* root_;
2265 return {
this,
true };
2269 return {
this,
true, options };
2273 return {
this,
true };
2277 return {
this,
true, options };
2289 return DepthFirstIterator();
2292 inline Element::ConstDepthFirstIterator Element::end()
const {
2293 return ConstDepthFirstIterator();
2297 return {
this,
false };
2301 return {
this,
false, options };
2305 return {
this,
false };
2309 return {
this,
false, options };
2314 return { NAN, NAN, NAN, NAN };
2322 using Element::Element;
2324 operator Point()
const {
2326 return std::make_pair(this->x(), this->y());
2333 Point(bbox.x1, bbox.y1),
2334 Point(bbox.x2, bbox.y1),
2335 Point(bbox.x1, bbox.y2),
2336 Point(bbox.x2, bbox.y2)
2340 virtual double x()
const {
return this->
find_numeric(
"x"); }
2341 virtual double y()
const {
return this->
find_numeric(
"y"); }
2359 static constexpr ElementKind static_kind = ElementKind::Defs;
2360 using Element::Element;
2370 std::unique_ptr<Element> clone_element_impl()
const override {
return clone_as<Defs>(); }
2376 class Stop :
public Element {
2378 static constexpr ElementKind static_kind = ElementKind::Stop;
2380 using Element::Element;
2381 ElementKind kind()
const override {
return static_kind; }
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));
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);
2394 std::unique_ptr<Element> clone_element_impl()
const override {
return clone_as<Stop>(); }
2398 class GradientElement :
public Element {
2400 using Element::Element;
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");
2408 return "url(#" + gradient_id +
")";
2412 void add_stop(std::string offset, std::string color) {
2413 this->add_child<Stop>(std::move(offset), std::move(color));
2416 void add_stop(std::string offset, std::string color,
double opacity) {
2417 this->add_child<Stop>(std::move(offset), std::move(color), opacity);
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");
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);
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);
2445 static std::string percent(
double value) {
2446 std::stringstream ss;
2447 ss << std::fixed << std::setprecision(1) << value <<
"%";
2455 class LinearGradient :
public detail::GradientElement {
2457 static constexpr ElementKind static_kind = ElementKind::LinearGradient;
2458 LinearGradient() =
default;
2459 using detail::GradientElement::GradientElement;
2460 ElementKind kind()
const override {
return static_kind; }
2462 explicit LinearGradient(std::string
id) {
2466 LinearGradient& horizontal() {
2467 return endpoints(
"0%",
"0%",
"100%",
"0%");
2470 LinearGradient& vertical() {
2471 return endpoints(
"0%",
"0%",
"0%",
"100%");
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));
2482 LinearGradient& stop(std::string offset, std::string color) {
2483 add_stop(std::move(offset), std::move(color));
2487 LinearGradient& stop(std::string offset,
const Color& color) {
2488 return stop(std::move(offset),
static_cast<std::string
>(color));
2491 LinearGradient& stop(std::string offset, std::string color,
double opacity) {
2492 add_stop(std::move(offset), std::move(color), opacity);
2496 LinearGradient& stop(std::string offset,
const Color& color,
double opacity) {
2497 return stop(std::move(offset),
static_cast<std::string
>(color), opacity);
2500 LinearGradient& solid_segments(std::initializer_list<std::string> colors) {
2501 set_solid_segments(colors);
2506 std::unique_ptr<Element> clone_element_impl()
const override {
return clone_as<LinearGradient>(); }
2510 class RadialGradient :
public detail::GradientElement {
2512 static constexpr ElementKind static_kind = ElementKind::RadialGradient;
2513 RadialGradient() =
default;
2514 using detail::GradientElement::GradientElement;
2515 ElementKind kind()
const override {
return static_kind; }
2517 explicit RadialGradient(std::string
id) {
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));
2527 RadialGradient& radius(std::string r) {
2528 this->set_attr(
"r", std::move(r));
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));
2538 RadialGradient& stop(std::string offset, std::string color) {
2539 add_stop(std::move(offset), std::move(color));
2543 RadialGradient& stop(std::string offset,
const Color& color) {
2544 return stop(std::move(offset),
static_cast<std::string
>(color));
2547 RadialGradient& stop(std::string offset, std::string color,
double opacity) {
2548 add_stop(std::move(offset), std::move(color), opacity);
2552 RadialGradient& stop(std::string offset,
const Color& color,
double opacity) {
2553 return stop(std::move(offset),
static_cast<std::string
>(color), opacity);
2556 RadialGradient& solid_segments(std::initializer_list<std::string> colors) {
2557 set_solid_segments(colors);
2562 std::unique_ptr<Element> clone_element_impl()
const override {
return clone_as<RadialGradient>(); }
2566 class Symbol :
public Element {
2568 static constexpr ElementKind static_kind = ElementKind::Symbol;
2570 using Element::Element;
2572 explicit Symbol(std::string
id) {
2577 std::string
href()
const;
2582 Use use(
double x,
double y)
const;
2584 Use use(
double x,
double y,
double width,
double height)
const;
2587 std::unique_ptr<Element> clone_element_impl()
const override {
return clone_as<Symbol>(); }
2593 static constexpr ElementKind static_kind = ElementKind::Use;
2597 explicit Use(std::string href) {
2598 set_attr(
"href", std::move(href));
2601 Use(std::string href,
double x,
double y) : Use(std::move(href)) {
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);
2614 set_attr(
"xlink:href", std::move(href));
2622 std::unique_ptr<Element> clone_element_impl()
const override {
return clone_as<Use>(); }
2626 friend class Element;
2628 std::map<std::string, Element*> id_index_;
2629 Defs* defs_ =
nullptr;
2632 class Style :
public Element {
2634 static constexpr ElementKind static_kind = ElementKind::Style;
2636 using Element::Element;
2643 std::string svg_to_string(
const size_t)
const override;
2644 std::unique_ptr<Element> clone_element_impl()
const override;
2647 static constexpr ElementKind static_kind = ElementKind::SVG;
2650 { {
"xmlns",
"http://www.w3.org/2000/svg" } }
2652 set_owner_svg(
this);
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);
2664 SVG(
SVG&& other) noexcept :
2665 Shape(std::move(other)),
2666 id_index_(std::move(other.id_index_)),
2669 refresh_special_children();
2670 set_owner_svg(
this);
2674 SVG& operator=(
SVG&& other)
noexcept {
2675 if (
this != &other) {
2676 Shape::operator=(std::move(other));
2677 id_index_ = std::move(other.id_index_);
2680 refresh_special_children();
2681 set_owner_svg(
this);
2687 SVG& operator=(
const SVG& other) =
delete;
2699 this->
style(key).set_attrs(attrs);
2705 return this->
css->media_queries[query][key];
2715 template<
typename T>
2721 template<
typename T>
2727 template<
typename T>
2729 const std::string& selector,
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];
2745 if (!this->defs_) this->defs_ = this->add_child<Defs>();
2749 template<
typename T,
typename... Args>
2750 typename std::enable_if<!std::is_same<T, Defs>::value, T*>::type add_child(Args&&... args) {
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_;
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;
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;
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;
2775 template<
typename T>
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);
2784 template<
typename T>
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);
2795 BoundingBox get_bbox()
const override;
2798 std::unique_ptr<Element> clone_element_impl()
const override {
2799 return detail::make_unique<SVG>(*
this);
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());
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());
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);
2827 this->id_index_[id] = &element;
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);
2838 void rebuild_id_index() {
2839 this->id_index_.clear();
2840 this->register_subtree_ids();
2843 ChildIterator defs_insert_position() {
2844 if (!this->css)
return this->children.begin();
2846 for (
auto it = this->children.begin(); it != this->children.end(); ++it) {
2847 if (it->get() == this->css)
return it + 1;
2849 return this->children.begin();
2854 inline SVG* Element::owner_svg() {
2855 return this->owner_;
2858 inline const SVG* Element::owner_svg()
const {
2859 return this->owner_;
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);
2869 inline Element& Element::id(
const std::string& value) {
2870 const auto old_indexed_id = this->indexed_id_;
2871 auto* root = this->owner_svg();
2873 if (value.empty()) {
2874 if (root && !old_indexed_id.empty()) {
2875 root->unregister_id(*
this, old_indexed_id);
2877 this->mutable_attrs().erase(
"id");
2878 this->indexed_id_.clear();
2882 if (root && old_indexed_id != value) {
2883 root->register_id(*
this, value);
2885 if (root && !old_indexed_id.empty() && old_indexed_id != value) {
2886 root->unregister_id(*
this, old_indexed_id);
2889 this->mutable_attrs()[
"id"] = value;
2890 this->indexed_id_ = root ? value :
"";
2894 inline std::string Element::id()
const {
2895 return this->get_attr(
"id");
2898 inline void Element::set_attr_value(
const std::string& key,
const std::string& value) {
2903 AttributeMap::set_attr_value(key, value);
2908 return AttributeMap::make_attr_setter(key);
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_;
2918 if (previous.empty()) {
2919 this->mutable_attrs().erase(
"id");
2921 this->mutable_attrs()[
"id"] = previous;
2928 inline void Element::register_subtree_ids() {
2929 this->register_own_id();
2930 for (
auto& child : this->children) {
2931 child->register_subtree_ids();
2935 inline void Element::unregister_subtree_ids() {
2936 this->unregister_own_id();
2937 for (
auto& child : this->children) {
2938 child->unregister_subtree_ids();
2942 inline void Element::register_own_id() {
2943 const auto current_id = this->id();
2944 if (current_id.empty())
return;
2946 if (
auto* root = this->owner_svg()) {
2947 root->register_id(*
this, current_id);
2948 this->indexed_id_ = current_id;
2952 inline void Element::unregister_own_id() {
2953 if (this->indexed_id_.empty())
return;
2955 if (
auto* root = this->owner_svg()) {
2956 root->unregister_id(*
this, this->indexed_id_);
2958 this->indexed_id_.clear();
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;
2967 this->children.clear();
2972 if (child->id() ==
id)
return *child;
2979 if (child->id() ==
id)
return *child;
2986 if (child->id() ==
id)
return child;
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");
2996 return "#" + symbol_id;
3006 return Use(this->
href(), x, y);
3010 return Use(this->
href(), x, y, width, height);
3015 static constexpr ElementKind static_kind = ElementKind::Path;
3019 template<
typename T>
3024 this->set_attr(
"d",
"M " + std::to_string(x) +
" " + std::to_string(y));
3029 template<
typename T>
3036 if (!this->has_attr(
"d"))
3039 this->mutable_attrs()[
"d"] +=
" L " + std::to_string(x) +
3040 " " + std::to_string(y);
3043 inline void line_to(std::pair<double, double> coord) {
3044 this->
line_to(coord.first, coord.second);
3049 this->
line_to(x_start, y_start);
3053 std::unique_ptr<Element> clone_element_impl()
const override {
3054 return clone_as<Path>();
3063 class Text :
public Element {
3065 static constexpr ElementKind static_kind = ElementKind::Text;
3067 using Element::Element;
3070 Text(
double x,
double y, std::string _content) {
3076 Text(std::pair<double, double> xy, std::string _content) :
3077 Text(xy.first, xy.second, _content) {};
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>();
3091 class Title :
public Element {
3107 std::unique_ptr<Element> clone_element_impl()
const override {
3108 return clone_as<Title>();
3114 static constexpr ElementKind static_kind = ElementKind::Group;
3115 using Element::Element;
3119 std::unique_ptr<Element> clone_element_impl()
const override {
return clone_as<Group>(); }
3127 static constexpr ElementKind static_kind = ElementKind::Line;
3132 Line(
double x1,
double x2,
double y1,
double y2) :
Shape({
3139 Line(Point x, Point y) : Line(x.first, y.first, x.second, y.second) {};
3141 virtual double x()
const override {
return x1() + (x2() - x1()) / 2; }
3142 virtual double y()
const override {
return y1() + (y2() - y1()) / 2; }
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; }
3154 std::pair<double, double>
along(
double percent)
const;
3157 Element::BoundingBox
get_bbox()
const override;
3158 std::unique_ptr<Element> clone_element_impl()
const override {
return clone_as<Line>(); }
3163 static constexpr ElementKind static_kind = ElementKind::Rect;
3169 double x,
double y,
double width,
double height) :
3177 Element::BoundingBox
get_bbox()
const override;
3180 std::unique_ptr<Element> clone_element_impl()
const override {
return clone_as<Rect>(); }
3185 static constexpr ElementKind static_kind = ElementKind::Circle;
3190 Circle(
double cx,
double cy,
double radius) :
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;
3207 std::unique_ptr<Element> clone_element_impl()
const override {
return clone_as<Circle>(); }
3210 class Polygon :
public Element {
3212 static constexpr ElementKind static_kind = ElementKind::Polygon;
3213 Polygon() =
default;
3214 using Element::Element;
3217 Polygon(
const std::vector<Point>& points) {
3219 std::string point_str;
3220 for (
auto& pt : points)
3222 this->set_attr(
"points", point_str);
3226 std::unique_ptr<Element> clone_element_impl()
const override {
return clone_as<Polygon>(); }
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 });
3236 double font_size = get_attr<double>(
"font-size", 16);
3237 if (!(font_size > 0)) font_size = 16;
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;
3246 const auto anchor = this->get_attr(
"text-anchor",
"start");
3247 if (anchor ==
"middle") {
3249 }
else if (anchor ==
"end") {
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") {
3261 }
else if (baseline ==
"text-after-edge" || baseline ==
"text-bottom") {
3265 return include_stroke_width({ x1, x1 + width, y1, y1 + height });
3269 return include_stroke_width({ std::min(x1(), x2()), std::max(x1(), x2()),
3270 std::min(y1(), y2()), std::max(y1(), y2()) });
3274 double x = this->x(), y = this->y(),
3276 return include_stroke_width({ x, x +
width, y, y +
height });
3280 double x = this->x(), y = this->y(), radius = this->radius();
3282 return include_stroke_width({
3295 double x_pos, y_pos;
3298 double length = percent * this->length();
3299 double discrim = std::sqrt(4 * pow(length, 2) * (1 / (1 + pow(slope(), 2))));
3301 double x_a = (2 * x1() + discrim) / 2;
3302 double x_b = (2 * x1() - discrim) / 2;
3305 if ((x_a > x1() && x_a > x2()) || (x_a < x1() && x_a < x2()))
3308 y_pos = slope() * (x_pos - x1()) + y1();
3314 y_pos = y1() - percent * this->length();
3316 y_pos = y1() + percent * this->length();
3319 return std::make_pair(x_pos, y_pos);
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');
3328 for (
const auto& pair : attrs) {
3332 append_escaped_xml(out, pair.second);
3339 const std::string& tag,
3340 const std::string& content,
3341 const size_t indent_level) {
3343 append_open_tag(out, indent_level, tag, element.attrs());
3345 append_escaped_xml(out, content);
3354 inline bool Element::uses_plain_xml() {
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;
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()) {
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);
3379 out += child->svg_to_string(level + 1);
3380 if (out.size() != start) out +=
'\n';
3382 out.append(level,
'\t');
3388 inline std::string Element::svg_to_string(
size_t level)
const {
3390 append_plain_xml(out, level);
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) {
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";
3409 auto indent = std::string(indent_level,
'\t');
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";
3416 ret +=
to_string(this->css, indent_level);
3420 ret += indent +
"\t\t@media " + media.first +
" {\n" +
3421 to_string(media.second, indent_level + 1) +
3422 indent +
"\t\t" +
"}\n";
3427 ret += indent +
"\t\t@keyframes " + anim.first +
" {\n" +
3428 to_string(anim.second, indent_level + 1) +
3429 indent +
"\t\t" +
"}\n";
3432 ret += indent +
"\t]]>\n";
3433 return ret + indent +
"</style>";
3439 inline std::unique_ptr<Element> SVG::Style::clone_element_impl()
const {
3440 return clone_as<Style>();
3443 inline std::string Text::svg_to_string(
const size_t indent_level)
const {
3452 layout_bbox_ = bbox;
3453 has_layout_bbox_ =
true;
3458 layout_bbox_padding_ = padding;
3463 return bbox_padding({ padding, padding, padding, padding });
3467 has_layout_bbox_ =
false;
3473 return measured_layout_bbox();
3477 if (has_layout_bbox_)
return layout_bbox_;
3479 if (std::isnan(bbox.x1) || std::isnan(bbox.x2) ||
3480 std::isnan(bbox.y1) || std::isnan(bbox.y2)) {
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
3491 inline detail::AffineTransform Element::transform_for(
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")));
3498 return parent_transform;
3502 inline unsigned alignment_count_bits(
Alignment value) {
3505 count += value & 1u;
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));
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;
3520 const auto width = element.get_attr<
double>(
"stroke-width", 1);
3521 return width > 0 ? width : 0;
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) {
3538 inline double bbox_center_x(
const Element::BoundingBox& bbox) {
3539 return bbox.x1 + (bbox.x2 - bbox.x1) / 2;
3542 inline double bbox_center_y(
const Element::BoundingBox& bbox) {
3543 return bbox.y1 + (bbox.y2 - bbox.y1) / 2;
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");
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");
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 };
3570 validate_appendable();
3572 throw std::logic_error(
"rotate_about_bbox requires an owning element transform list");
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");
3578 return rotate(degrees,
3579 detail::bbox_anchor_x(bbox, x_anchor),
3580 detail::bbox_anchor_y(bbox, y_anchor));
3584 const auto href = this->get_attr(
"href", this->get_attr(
"xlink:href"));
3585 if (href.empty() || href[0] !=
'#')
return { NAN, NAN, NAN, NAN };
3587 const auto* root = this->owner_svg();
3588 if (!root)
return { NAN, NAN, NAN, NAN };
3590 const auto* referenced = root->get_element_by_id(href.substr(1));
3591 if (!referenced || referenced ==
this)
return { NAN, NAN, NAN, NAN };
3594 if (!detail::bbox_is_measured(bbox))
return bbox;
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];
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
3611 return include_stroke_width(bbox);
3614 bbox = { bbox.x1 + x, bbox.x2 + x, bbox.y1 + y, bbox.y2 + y };
3615 return include_stroke_width(bbox);
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);
3630 if (!detail::bbox_is_measured(bbox))
return bbox;
3631 return { bbox.x1 + x, bbox.x2 + x, bbox.y1 + y, bbox.y2 + y };
3644 static_cast<Alignment>(RelativeAlignment::Left) |
3645 static_cast<Alignment>(RelativeAlignment::Top) |
3646 static_cast<Alignment>(RelativeAlignment::Right) |
3647 static_cast<Alignment>(RelativeAlignment::Bottom);
3650 static_cast<Alignment>(Anchor::Center) |
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");
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");
3663 if ((alignment & ~(relative_mask | anchor_mask)) != 0) {
3664 throw std::invalid_argument(
"snap_to received unknown alignment bits");
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");
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;
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);
3692 dy = target_box.y2 - source_box.y2;
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);
3700 dx = target_box.x2 - source_box.x2;
3704 this->transform().translate(dx + offset.first, dy + offset.second);
3711 return align_to(target, axis, Anchor::Center, offset);
3718 if (axis != Axis::X && axis != Axis::Y) {
3719 throw std::invalid_argument(
"align_to requires a valid axis");
3721 if (anchor != Anchor::Start && anchor != Anchor::Center && anchor != Anchor::End) {
3722 throw std::invalid_argument(
"align_to requires a valid anchor");
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");
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);
3739 dx += target_box.x2 - source_box.x2;
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);
3747 dy += target_box.y2 - source_box.y2;
3751 this->transform().translate(dx, dy);
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());
3760 svg_child->responsive_autoscale(options);
3762 svg_child->autoscale(options);
3765 child->autoscale_nested_svgs(options, responsive);
3771 Element::BoundingBox bbox =
3773 ? Element::BoundingBox(NAN, NAN, NAN, NAN)
3774 : this->measured_layout_bbox();
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;
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;
3788 std::stringstream viewbox;
3789 viewbox << std::fixed << std::setprecision(1)
3794 this->set_attr(
"viewBox", viewbox.str());
3797 inline void Element::autoscale(
const double margin) {
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;
3806 width * margin, width * margin,
3807 height * margin, height * margin
3809 this->autoscale(options);
3812 inline void Element::autoscale(
const Margins& margins) {
3823 this->autoscale_nested_svgs(options,
false);
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;
3829 this->set_attr(
"width", width)
3830 .set_attr(
"height", height);
3832 this->set_viewbox_from_bbox(bbox, options.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;
3843 width * margin, width * margin,
3844 height * margin, height * margin
3854 this->autoscale_nested_svgs(options,
true);
3856 this->set_viewbox_from_bbox(this->get_autoscale_bbox(), options.margins);
3862 for (
auto element = elements.begin(); element != elements.end(); ++element) {
3863 const auto* current = *element;
3864 if (visible_only && !detail::renders_in_place(current)) {
3867 auto current_box = current->measured_layout_bbox();
3868 if (!detail::bbox_is_measured(current_box)) {
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 });
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;
3888 Element::ChildMap child_map;
3890 child_map[child->tag()].push_back(child);
3896 Element::ConstChildMap child_map;
3898 child_map[child->tag()].push_back(child);
3904 std::vector<Element*> ret;
3905 for (
auto* child : this->
descendants()) ret.push_back(child);
3912 std::vector<const Element*> ret;
3913 for (
const auto* child : this->
descendants()) ret.push_back(child);
3923 ret << std::move(left) << std::move(right);
3927 svg_child->autoscale(margins);
3930 double x = 0, height = 0;
3932 svg_child->set_attr(
"x", x).set_attr(
"y", 0);
3933 x += svg_child->width();
3934 height = std::max(height, svg_child->height());
3937 ret.set_attr(
"width", x).set_attr(
"height", height);
3941 inline std::vector<Point> bounding_polygon(std::vector<Shape*>& shapes) {
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));
3954 inline SVG merge(std::vector<SVG>& frames,
const double width,
const int max_frame_width) {
3959 double x = 0, y = 0, total_width = 0, total_height = 0;
3960 for (
auto& frame : frames) {
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);
3971 double current_height = 0;
3972 for (
auto& frame : frames) {
3974 if ((x + frame.width()) > width) {
3975 total_width = std::max(total_width, x);
3977 y += current_height;
3981 frame.set_attr(
"x", x).set_attr(
"y", y);
3983 current_height = std::max(current_height, frame.height());
3984 root << std::move(frame);
3987 total_height = y + current_height;
3990 root.set_attr(
"viewBox") << 0 <<
" " << 0 <<
" " << total_width <<
" " << total_height;
3991 root.set_attr(
"width", total_width).set_attr(
"height", total_height);
3998 const double duration = (double)frames.size() / fps;
3999 const double frame_step = 1.0 / fps;
4000 int current_frame = 0;
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);
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));
4014 root << std::move(frame);
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);
4028 double width = 0, height = 0;
4032 width = std::max(width, child->width());
4033 height = std::max(height, child->height());
4036 root.set_attr(
"viewBox",
"0 0 " + std::to_string(width) +
" " + std::to_string(height));
4040 child->set_attr(
"x", (width - child->width())/2).set_attr(
"y", (height - child->height())/2);