diff --git a/src/hb-raster-svg-base.cc b/src/hb-raster-svg-base.cc new file mode 100644 index 000000000..641b005d5 --- /dev/null +++ b/src/hb-raster-svg-base.cc @@ -0,0 +1,497 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#include "hb.hh" + +#include "hb-raster-svg-base.hh" +#include "hb-raster-svg-parse.hh" + +void +svg_parse_style_props (hb_svg_str_t style, hb_svg_style_props_t *out) +{ + if (style.is_null ()) return; + const char *p = style.data; + const char *end = style.data + style.len; + while (p < end) + { + while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || *p == ';')) + p++; + if (p >= end) break; + const char *name_start = p; + while (p < end && *p != ':' && *p != ';') + p++; + const char *name_end = p; + while (name_end > name_start && + (name_end[-1] == ' ' || name_end[-1] == '\t' || name_end[-1] == '\n' || name_end[-1] == '\r')) + name_end--; + if (p >= end || *p != ':') + { + while (p < end && *p != ';') p++; + continue; + } + p++; /* skip ':' */ + const char *value_start = p; + while (p < end && *p != ';') + p++; + const char *value_end = p; + while (value_start < value_end && + (*value_start == ' ' || *value_start == '\t' || *value_start == '\n' || *value_start == '\r')) + value_start++; + while (value_end > value_start && + (value_end[-1] == ' ' || value_end[-1] == '\t' || value_end[-1] == '\n' || value_end[-1] == '\r')) + value_end--; + + hb_svg_str_t prop_name = {name_start, (unsigned) (name_end - name_start)}; + hb_svg_str_t prop_value = {value_start, (unsigned) (value_end - value_start)}; + if (prop_name.len) + { + switch (hb_svg_ascii_lower (prop_name.data[0])) + { + case 'c': + if (prop_name.len == 9 && prop_name.eq_ascii_ci ("clip-path")) out->clip_path = prop_value; + else if (prop_name.len == 5 && prop_name.eq_ascii_ci ("color")) out->color = prop_value; + else if (prop_name.len == 2 && prop_name.eq_ascii_ci ("cx")) out->cx = prop_value; + else if (prop_name.len == 2 && prop_name.eq_ascii_ci ("cy")) out->cy = prop_value; + break; + case 'd': + if (prop_name.len == 7 && prop_name.eq_ascii_ci ("display")) out->display = prop_value; + else if (prop_name.len == 1 && prop_name.eq_ascii_ci ("d")) out->d = prop_value; + break; + case 'f': + if (prop_name.len == 4 && prop_name.eq_ascii_ci ("fill")) out->fill = prop_value; + else if (prop_name.len == 12 && prop_name.eq_ascii_ci ("fill-opacity")) out->fill_opacity = prop_value; + else if (prop_name.len == 2 && prop_name.eq_ascii_ci ("fx")) out->fx = prop_value; + else if (prop_name.len == 2 && prop_name.eq_ascii_ci ("fy")) out->fy = prop_value; + else if (prop_name.len == 2 && prop_name.eq_ascii_ci ("fr")) out->fr = prop_value; + break; + case 'g': + if ((prop_name.len == 13 && prop_name.eq_ascii_ci ("gradientunits")) || + (prop_name.len == 14 && prop_name.eq_ascii_ci ("gradient-units"))) out->gradient_units = prop_value; + else if ((prop_name.len == 17 && prop_name.eq_ascii_ci ("gradienttransform")) || + (prop_name.len == 18 && prop_name.eq_ascii_ci ("gradient-transform"))) out->gradient_transform = prop_value; + break; + case 'h': + if (prop_name.len == 6 && prop_name.eq_ascii_ci ("height")) out->height = prop_value; + break; + case 'o': + if (prop_name.len == 7 && prop_name.eq_ascii_ci ("opacity")) out->opacity = prop_value; + else if (prop_name.len == 6 && prop_name.eq_ascii_ci ("offset")) out->offset = prop_value; + break; + case 'p': + if (prop_name.len == 6 && prop_name.eq_ascii_ci ("points")) out->points = prop_value; + break; + case 'r': + if (prop_name.len == 1 && prop_name.eq_ascii_ci ("r")) out->r = prop_value; + else if (prop_name.len == 2 && prop_name.eq_ascii_ci ("rx")) out->rx = prop_value; + else if (prop_name.len == 2 && prop_name.eq_ascii_ci ("ry")) out->ry = prop_value; + break; + case 's': + if (prop_name.len == 10 && prop_name.eq_ascii_ci ("stop-color")) out->stop_color = prop_value; + else if (prop_name.len == 12 && prop_name.eq_ascii_ci ("stop-opacity")) out->stop_opacity = prop_value; + else if ((prop_name.len == 12 && prop_name.eq_ascii_ci ("spreadmethod")) || + (prop_name.len == 13 && prop_name.eq_ascii_ci ("spread-method"))) out->spread_method = prop_value; + break; + case 't': + if (prop_name.len == 9 && prop_name.eq_ascii_ci ("transform")) out->transform = prop_value; + break; + case 'v': + if (prop_name.len == 10 && prop_name.eq_ascii_ci ("visibility")) out->visibility = prop_value; + break; + case 'w': + if (prop_name.len == 5 && prop_name.eq_ascii_ci ("width")) out->width = prop_value; + break; + case 'x': + if (prop_name.len == 1 && prop_name.eq_ascii_ci ("x")) out->x = prop_value; + else if (prop_name.len == 2 && prop_name.eq_ascii_ci ("x1")) out->x1 = prop_value; + else if (prop_name.len == 2 && prop_name.eq_ascii_ci ("x2")) out->x2 = prop_value; + break; + case 'y': + if (prop_name.len == 1 && prop_name.eq_ascii_ci ("y")) out->y = prop_value; + else if (prop_name.len == 2 && prop_name.eq_ascii_ci ("y1")) out->y1 = prop_value; + else if (prop_name.len == 2 && prop_name.eq_ascii_ci ("y2")) out->y2 = prop_value; + break; + default: + break; + } + } + + if (p < end && *p == ';') p++; + } +} + +float +svg_parse_number_or_percent (hb_svg_str_t s, bool *is_percent) +{ + if (is_percent) *is_percent = false; + s = s.trim (); + if (!s.len) return 0.f; + if (s.data[s.len - 1] == '%') + { + if (is_percent) *is_percent = true; + hb_svg_str_t n = {s.data, s.len - 1}; + return n.to_float () / 100.f; + } + return s.to_float (); +} + +hb_svg_str_t +hb_raster_svg_find_href_attr (const hb_svg_xml_parser_t &parser) +{ + hb_svg_str_t href = parser.find_attr ("href"); + if (href.is_null ()) + href = parser.find_attr ("xlink:href"); + return href; +} + +bool +hb_raster_svg_parse_id_ref (hb_svg_str_t s, + hb_svg_str_t *out_id, + hb_svg_str_t *out_tail) +{ + if (out_id) *out_id = {}; + if (out_tail) *out_tail = {}; + s = s.trim (); + + if (s.len && s.data[0] == '#') + { + hb_svg_str_t id = {s.data + 1, s.len - 1}; + id = id.trim (); + if (!id.len) + return false; + if (out_id) *out_id = id; + return true; + } + + if (!s.starts_with_ascii_ci ("url(")) + return false; + + const char *p = s.data + 4; + const char *end = s.data + s.len; + while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++; + + const char *q = p; + char quote = 0; + while (q < end) + { + char c = *q; + if (quote) + { + if (c == quote) quote = 0; + } + else + { + if (c == '"' || c == '\'') quote = c; + else if (c == ')') break; + } + q++; + } + if (q >= end || *q != ')') + return false; + + hb_svg_str_t id = {(const char *) p, (unsigned) (q - p)}; + id = id.trim (); + if (id.len >= 2 && + ((id.data[0] == '\'' && id.data[id.len - 1] == '\'') || + (id.data[0] == '"' && id.data[id.len - 1] == '"'))) + { + id.data++; + id.len -= 2; + } + id = id.trim (); + if (id.len && id.data[0] == '#') + { + id.data++; + id.len--; + } + id = id.trim (); + if (!id.len) + return false; + + if (out_id) *out_id = id; + if (out_tail) + { + const char *tail = q + 1; + while (tail < end && (*tail == ' ' || *tail == '\t' || *tail == '\n' || *tail == '\r')) tail++; + *out_tail = {(const char *) tail, (unsigned) (end - tail)}; + } + return true; +} + +bool +hb_raster_svg_parse_local_id_ref (hb_svg_str_t s, + hb_svg_str_t *out_id, + hb_svg_str_t *out_tail) +{ + if (out_id) *out_id = {}; + if (out_tail) *out_tail = {}; + s = s.trim (); + + if (s.len && s.data[0] == '#') + { + hb_svg_str_t id = {s.data + 1, s.len - 1}; + id = id.trim (); + if (!id.len) + return false; + if (out_id) *out_id = id; + return true; + } + + if (!s.starts_with_ascii_ci ("url(")) + return false; + + hb_svg_str_t id; + if (!hb_raster_svg_parse_id_ref (s, &id, out_tail)) + return false; + + const char *p = s.data + 4; + const char *end = s.data + s.len; + while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++; + if (p < end && (*p == '\'' || *p == '"')) + { + p++; + while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++; + if (p >= end || *p != '#') + return false; + } + else if (p >= end || *p != '#') + return false; + + if (out_id) *out_id = id; + return true; +} + +bool +hb_raster_svg_find_element_by_id (const char *doc_start, + unsigned doc_len, + const OT::SVG::accelerator_t *svg_accel, + const OT::SVG::svg_doc_cache_t *doc_cache, + hb_svg_str_t id, + const char **found) +{ + *found = nullptr; + if (!doc_start || !doc_len || !id.len) + return false; + + if (doc_cache && svg_accel) + { + unsigned start = 0, end = 0; + OT::SVG::svg_id_span_t key = {id.data, id.len}; + if (svg_accel->doc_cache_find_id_span (doc_cache, key, &start, &end)) + { + if (start < doc_len && end <= doc_len && start < end) + { + *found = doc_start + start; + return true; + } + } + } + + hb_svg_xml_parser_t search (doc_start, doc_len); + while (true) + { + hb_svg_token_type_t tok = search.next (); + if (tok == SVG_TOKEN_EOF) break; + if (tok != SVG_TOKEN_OPEN_TAG && tok != SVG_TOKEN_SELF_CLOSE_TAG) continue; + hb_svg_str_t attr_id = search.find_attr ("id"); + if (attr_id.len == id.len && 0 == memcmp (attr_id.data, id.data, id.len)) + { + *found = search.tag_start; + return true; + } + } + return false; +} + +bool +hb_raster_svg_parse_viewbox (hb_svg_str_t viewbox_str, + float *x, + float *y, + float *w, + float *h) +{ + if (!viewbox_str.len) + return false; + hb_svg_float_parser_t vb_fp (viewbox_str); + float vb_x = vb_fp.next_float (); + float vb_y = vb_fp.next_float (); + float vb_w = vb_fp.next_float (); + float vb_h = vb_fp.next_float (); + if (vb_w <= 0.f || vb_h <= 0.f) + return false; + if (x) *x = vb_x; + if (y) *y = vb_y; + if (w) *w = vb_w; + if (h) *h = vb_h; + return true; +} + +static inline float +svg_align_offset (hb_svg_str_t align, + float leftover, + char axis) +{ + if (leftover <= 0.f) return 0.f; + if ((axis == 'x' && align.starts_with_ascii_ci ("xMin")) || + (axis == 'y' && (align.eq_ascii_ci ("xMinYMin") || + align.eq_ascii_ci ("xMidYMin") || + align.eq_ascii_ci ("xMaxYMin")))) + return 0.f; + if ((axis == 'x' && align.starts_with_ascii_ci ("xMax")) || + (axis == 'y' && (align.eq_ascii_ci ("xMinYMax") || + align.eq_ascii_ci ("xMidYMax") || + align.eq_ascii_ci ("xMaxYMax")))) + return leftover; + return leftover * 0.5f; +} + +bool +hb_raster_svg_compute_viewbox_transform (float viewport_w, + float viewport_h, + float vb_x, + float vb_y, + float vb_w, + float vb_h, + hb_svg_str_t preserve_aspect_ratio, + hb_svg_transform_t *out) +{ + if (!(viewport_w > 0.f && viewport_h > 0.f && vb_w > 0.f && vb_h > 0.f)) + return false; + + hb_svg_str_t par = preserve_aspect_ratio.trim (); + if (par.starts_with_ascii_ci ("defer")) + { + const char *p = par.data + 5; + const char *end = par.data + par.len; + while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++; + par = hb_svg_str_t (p, (unsigned) (end - p)); + } + if (!par.len) + par = hb_svg_str_t ("xMidYMid meet", 12); + + bool is_none = false; + bool is_slice = false; + hb_svg_str_t align = par; + const char *p = par.data; + const char *end = par.data + par.len; + while (p < end && *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r') p++; + align = hb_svg_str_t (par.data, (unsigned) (p - par.data)).trim (); + + if (par.starts_with_ascii_ci ("none")) + is_none = true; + else if (align.starts_with_ascii_ci ("x")) + { + const char *mode = p; + while (mode < end && (*mode == ' ' || *mode == '\t' || *mode == '\n' || *mode == '\r')) mode++; + if (mode < end && hb_svg_str_t (mode, (unsigned) (end - mode)).starts_with_ascii_ci ("slice")) + is_slice = true; + } + + hb_svg_transform_t t; + if (is_none) + { + t.xx = viewport_w / vb_w; + t.yy = viewport_h / vb_h; + t.dx = -vb_x * t.xx; + t.dy = -vb_y * t.yy; + *out = t; + return true; + } + + float sx = viewport_w / vb_w; + float sy = viewport_h / vb_h; + float s = is_slice ? hb_max (sx, sy) : hb_min (sx, sy); + float scaled_w = vb_w * s; + float scaled_h = vb_h * s; + float leftover_x = viewport_w - scaled_w; + float leftover_y = viewport_h - scaled_h; + + if (!align.starts_with_ascii_ci ("x")) + align = hb_svg_str_t ("xMidYMid", 8); + + t.xx = s; + t.yy = s; + t.dx = svg_align_offset (align, leftover_x, 'x') - vb_x * s; + t.dy = svg_align_offset (align, leftover_y, 'y') - vb_y * s; + *out = t; + return true; +} + +bool +hb_raster_svg_compute_use_target_viewbox_transform (hb_svg_xml_parser_t &target_parser, + float use_w, + float use_h, + hb_svg_transform_t *out) +{ + if (!(target_parser.tag_name.eq ("svg") || target_parser.tag_name.eq ("symbol"))) + return false; + + float viewport_w = use_w; + float viewport_h = use_h; + hb_svg_style_props_t target_style_props; + svg_parse_style_props (target_parser.find_attr ("style"), &target_style_props); + if (viewport_w <= 0.f) + viewport_w = hb_raster_svg_parse_non_percent_length (svg_pick_attr_or_style (target_parser, target_style_props.width, "width")); + if (viewport_h <= 0.f) + viewport_h = hb_raster_svg_parse_non_percent_length (svg_pick_attr_or_style (target_parser, target_style_props.height, "height")); + + float vb_x = 0.f, vb_y = 0.f, vb_w = 0.f, vb_h = 0.f; + if (!hb_raster_svg_parse_viewbox (target_parser.find_attr ("viewBox"), &vb_x, &vb_y, &vb_w, &vb_h)) + return false; + + if (!(viewport_w > 0.f && viewport_h > 0.f)) + { + viewport_w = vb_w; + viewport_h = vb_h; + } + + return hb_raster_svg_compute_viewbox_transform (viewport_w, viewport_h, vb_x, vb_y, vb_w, vb_h, + target_parser.find_attr ("preserveAspectRatio"), + out); +} + +void +hb_raster_svg_parse_use_geometry (hb_svg_xml_parser_t &parser, + float *x, + float *y, + float *w, + float *h) +{ + hb_svg_style_props_t style_props; + svg_parse_style_props (parser.find_attr ("style"), &style_props); + + if (x) *x = hb_raster_svg_parse_non_percent_length (svg_pick_attr_or_style (parser, style_props.x, "x")); + if (y) *y = hb_raster_svg_parse_non_percent_length (svg_pick_attr_or_style (parser, style_props.y, "y")); + if (w) *w = hb_raster_svg_parse_non_percent_length (svg_pick_attr_or_style (parser, style_props.width, "width")); + if (h) *h = hb_raster_svg_parse_non_percent_length (svg_pick_attr_or_style (parser, style_props.height, "height")); +} + +float +hb_raster_svg_parse_non_percent_length (hb_svg_str_t s) +{ + bool is_percent = false; + float v = svg_parse_number_or_percent (s, &is_percent); + return is_percent ? 0.f : v; +} diff --git a/src/hb-raster-svg-base.hh b/src/hb-raster-svg-base.hh new file mode 100644 index 000000000..c7bdc9bd2 --- /dev/null +++ b/src/hb-raster-svg-base.hh @@ -0,0 +1,227 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#ifndef HB_RASTER_SVG_BASE_HH +#define HB_RASTER_SVG_BASE_HH + +#include "hb.hh" +#include "OT/Color/svg/svg.hh" + +#include +#include +#include + +static inline char +hb_svg_ascii_lower (char c) +{ + if (c >= 'A' && c <= 'Z') + return c + ('a' - 'A'); + return c; +} + +struct hb_svg_str_t +{ + const char *data; + unsigned len; + + hb_svg_str_t () : data (nullptr), len (0) {} + hb_svg_str_t (const char *d, unsigned l) : data (d), len (l) {} + + bool is_null () const { return !data; } + + bool eq (const char *s) const + { + unsigned slen = (unsigned) strlen (s); + return len == slen && memcmp (data, s, len) == 0; + } + + bool starts_with (const char *prefix) const + { + unsigned plen = (unsigned) strlen (prefix); + return len >= plen && memcmp (data, prefix, plen) == 0; + } + + bool eq_ascii_ci (const char *lit) const + { + unsigned n = (unsigned) strlen (lit); + if (len != n) return false; + for (unsigned i = 0; i < n; i++) + if (hb_svg_ascii_lower (data[i]) != hb_svg_ascii_lower (lit[i])) + return false; + return true; + } + + bool starts_with_ascii_ci (const char *lit) const + { + unsigned n = (unsigned) strlen (lit); + if (len < n) return false; + for (unsigned i = 0; i < n; i++) + if (hb_svg_ascii_lower (data[i]) != hb_svg_ascii_lower (lit[i])) + return false; + return true; + } + + float to_float () const + { + if (!data || !len) return 0.f; + char buf[64]; + unsigned n = hb_min (len, (unsigned) sizeof (buf) - 1); + memcpy (buf, data, n); + buf[n] = '\0'; + float v = strtof (buf, nullptr); + return isfinite (v) ? v : 0.f; + } + + hb_svg_str_t trim_left () const + { + const char *p = data; + unsigned l = len; + while (l && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) + { + p++; + l--; + } + return {p, l}; + } + + hb_svg_str_t trim () const + { + hb_svg_str_t s = trim_left (); + while (s.len && (s.data[s.len - 1] == ' ' || s.data[s.len - 1] == '\t' || + s.data[s.len - 1] == '\n' || s.data[s.len - 1] == '\r')) + s.len--; + return s; + } +}; + +struct hb_svg_style_props_t +{ + hb_svg_str_t fill; + hb_svg_str_t fill_opacity; + hb_svg_str_t opacity; + hb_svg_str_t transform; + hb_svg_str_t clip_path; + hb_svg_str_t display; + hb_svg_str_t color; + hb_svg_str_t visibility; + hb_svg_str_t offset; + hb_svg_str_t stop_color; + hb_svg_str_t stop_opacity; + hb_svg_str_t spread_method; + hb_svg_str_t gradient_units; + hb_svg_str_t gradient_transform; + hb_svg_str_t x; + hb_svg_str_t y; + hb_svg_str_t width; + hb_svg_str_t height; + hb_svg_str_t cx; + hb_svg_str_t cy; + hb_svg_str_t r; + hb_svg_str_t fx; + hb_svg_str_t fy; + hb_svg_str_t fr; + hb_svg_str_t rx; + hb_svg_str_t ry; + hb_svg_str_t x1; + hb_svg_str_t y1; + hb_svg_str_t x2; + hb_svg_str_t y2; + hb_svg_str_t points; + hb_svg_str_t d; +}; + +struct hb_svg_xml_parser_t; +struct hb_svg_transform_t; + +HB_INTERNAL void svg_parse_style_props (hb_svg_str_t style, hb_svg_style_props_t *out); +HB_INTERNAL float svg_parse_number_or_percent (hb_svg_str_t s, bool *is_percent); +HB_INTERNAL hb_svg_str_t hb_raster_svg_find_href_attr (const hb_svg_xml_parser_t &parser); +HB_INTERNAL bool hb_raster_svg_parse_id_ref (hb_svg_str_t s, + hb_svg_str_t *out_id, + hb_svg_str_t *out_tail); +HB_INTERNAL bool hb_raster_svg_parse_local_id_ref (hb_svg_str_t s, + hb_svg_str_t *out_id, + hb_svg_str_t *out_tail); +HB_INTERNAL bool hb_raster_svg_find_element_by_id (const char *doc_start, + unsigned doc_len, + const OT::SVG::accelerator_t *svg_accel, + const OT::SVG::svg_doc_cache_t *doc_cache, + hb_svg_str_t id, + const char **found); +HB_INTERNAL bool hb_raster_svg_parse_viewbox (hb_svg_str_t viewbox_str, + float *x, + float *y, + float *w, + float *h); +HB_INTERNAL bool hb_raster_svg_compute_viewbox_transform (float viewport_w, + float viewport_h, + float vb_x, + float vb_y, + float vb_w, + float vb_h, + hb_svg_str_t preserve_aspect_ratio, + hb_svg_transform_t *out); +HB_INTERNAL bool hb_raster_svg_compute_use_target_viewbox_transform (hb_svg_xml_parser_t &target_parser, + float use_w, + float use_h, + hb_svg_transform_t *out); +HB_INTERNAL void hb_raster_svg_parse_use_geometry (hb_svg_xml_parser_t &parser, + float *x, + float *y, + float *w, + float *h); +HB_INTERNAL float hb_raster_svg_parse_non_percent_length (hb_svg_str_t s); +static inline float +svg_parse_float_clamped01 (hb_svg_str_t s) +{ + return hb_clamp (s.to_float (), 0.f, 1.f); +} + +static inline bool +svg_str_is_inherit (hb_svg_str_t s) +{ + return s.trim ().eq_ascii_ci ("inherit"); +} + +static inline bool +svg_str_is_none (hb_svg_str_t s) +{ + return s.trim ().eq_ascii_ci ("none"); +} + +static inline bool +hb_raster_svg_tag_is_container (hb_svg_str_t tag) +{ + return tag.eq ("g") || tag.eq ("a") || tag.eq ("svg") || tag.eq ("symbol"); +} + +static inline bool +hb_raster_svg_tag_is_container_or_use (hb_svg_str_t tag) +{ + return hb_raster_svg_tag_is_container (tag) || tag.eq ("use"); +} + +#endif /* HB_RASTER_SVG_BASE_HH */ diff --git a/src/hb-raster-svg-bbox.cc b/src/hb-raster-svg-bbox.cc new file mode 100644 index 000000000..d229e31cf --- /dev/null +++ b/src/hb-raster-svg-bbox.cc @@ -0,0 +1,105 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#include "hb.hh" + +#include "hb-raster-svg-bbox.hh" + +static void +svg_bbox_move_to (hb_draw_funcs_t *dfuncs HB_UNUSED, + void *draw_data, + hb_draw_state_t *st HB_UNUSED, + float to_x, float to_y, + void *user_data HB_UNUSED) +{ + ((hb_extents_t<> *) draw_data)->add_point (to_x, to_y); +} + +static void +svg_bbox_line_to (hb_draw_funcs_t *dfuncs HB_UNUSED, + void *draw_data, + hb_draw_state_t *st HB_UNUSED, + float to_x, float to_y, + void *user_data HB_UNUSED) +{ + ((hb_extents_t<> *) draw_data)->add_point (to_x, to_y); +} + +static void +svg_bbox_quadratic_to (hb_draw_funcs_t *dfuncs HB_UNUSED, + void *draw_data, + hb_draw_state_t *st HB_UNUSED, + float control_x, float control_y, + float to_x, float to_y, + void *user_data HB_UNUSED) +{ + hb_extents_t<> *ext = (hb_extents_t<> *) draw_data; + ext->add_point (control_x, control_y); + ext->add_point (to_x, to_y); +} + +static void +svg_bbox_cubic_to (hb_draw_funcs_t *dfuncs HB_UNUSED, + void *draw_data, + hb_draw_state_t *st HB_UNUSED, + float control1_x, float control1_y, + float control2_x, float control2_y, + float to_x, float to_y, + void *user_data HB_UNUSED) +{ + hb_extents_t<> *ext = (hb_extents_t<> *) draw_data; + ext->add_point (control1_x, control1_y); + ext->add_point (control2_x, control2_y); + ext->add_point (to_x, to_y); +} + +static hb_draw_funcs_t * +svg_bbox_draw_funcs () +{ + static hb_draw_funcs_t *funcs = nullptr; + if (unlikely (!funcs)) + { + funcs = hb_draw_funcs_create (); + hb_draw_funcs_set_move_to_func (funcs, svg_bbox_move_to, nullptr, nullptr); + hb_draw_funcs_set_line_to_func (funcs, svg_bbox_line_to, nullptr, nullptr); + hb_draw_funcs_set_quadratic_to_func (funcs, svg_bbox_quadratic_to, nullptr, nullptr); + hb_draw_funcs_set_cubic_to_func (funcs, svg_bbox_cubic_to, nullptr, nullptr); + hb_draw_funcs_make_immutable (funcs); + } + return funcs; +} + +bool +hb_raster_svg_compute_shape_bbox (const hb_svg_shape_emit_data_t &shape, + hb_extents_t<> *bbox) +{ + hb_extents_t<> ext; + hb_svg_shape_emit_data_t tmp = shape; + hb_raster_svg_shape_path_emit (svg_bbox_draw_funcs (), &ext, &tmp); + if (ext.is_empty ()) return false; + *bbox = ext; + return true; +} diff --git a/src/hb-raster-svg-bbox.hh b/src/hb-raster-svg-bbox.hh new file mode 100644 index 000000000..46802e6d7 --- /dev/null +++ b/src/hb-raster-svg-bbox.hh @@ -0,0 +1,39 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#ifndef HB_RASTER_SVG_BBOX_HH +#define HB_RASTER_SVG_BBOX_HH + +#include "hb.hh" + +#include "hb-geometry.hh" +#include "hb-raster-svg-parse.hh" + +HB_INTERNAL bool +hb_raster_svg_compute_shape_bbox (const hb_svg_shape_emit_data_t &shape, + hb_extents_t<> *bbox); + +#endif /* HB_RASTER_SVG_BBOX_HH */ diff --git a/src/hb-raster-svg-clip.cc b/src/hb-raster-svg-clip.cc new file mode 100644 index 000000000..ca4ceeecb --- /dev/null +++ b/src/hb-raster-svg-clip.cc @@ -0,0 +1,538 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#include "hb.hh" + +#include "hb-raster-svg-clip.hh" + +#include "hb-raster.h" +#include "hb-raster-paint.hh" +#include "hb-raster-svg.hh" +#include "hb-raster-svg-base.hh" +#include "hb-decycler.hh" + +#include + +static inline bool +svg_transform_is_identity (const hb_svg_transform_t &t) +{ + return t.xx == 1.f && t.yx == 0.f && + t.xy == 0.f && t.yy == 1.f && + t.dx == 0.f && t.dy == 0.f; +} + +static bool +svg_parse_element_transform (hb_svg_xml_parser_t &parser, + hb_svg_transform_t *out) +{ + hb_svg_style_props_t style_props; + svg_parse_style_props (parser.find_attr ("style"), &style_props); + hb_svg_str_t transform = svg_pick_attr_or_style (parser, style_props.transform, "transform"); + if (!transform.len) + return false; + hb_raster_svg_parse_transform (transform, out); + return true; +} + +struct hb_svg_clip_collect_context_t +{ + hb_svg_defs_t *defs; + hb_svg_clip_path_def_t *clip; + const char *doc_start; + unsigned doc_len; + const OT::SVG::accelerator_t *svg_accel; + const OT::SVG::svg_doc_cache_t *doc_cache; + hb_decycler_t *use_decycler; + bool *had_alloc_failure; +}; + +static inline void +svg_clip_append_shape (hb_svg_clip_collect_context_t *ctx, + const hb_svg_shape_emit_data_t &shape, + const hb_svg_transform_t &transform) +{ + hb_svg_clip_shape_t clip_shape; + clip_shape.shape = shape; + if (!svg_transform_is_identity (transform)) + { + clip_shape.has_transform = true; + clip_shape.transform = transform; + } + ctx->defs->clip_shapes.push (clip_shape); + if (likely (!ctx->defs->clip_shapes.in_error ())) + ctx->clip->shape_count++; + else if (ctx->had_alloc_failure) + *ctx->had_alloc_failure = true; +} + +static void +svg_skip_subtree (hb_svg_xml_parser_t &parser) +{ + int depth = 1; + while (depth > 0) + { + hb_svg_token_type_t tok = parser.next (); + if (tok == SVG_TOKEN_EOF) break; + if (tok == SVG_TOKEN_CLOSE_TAG) depth--; + else if (tok == SVG_TOKEN_OPEN_TAG) depth++; + } +} + +static inline bool +svg_resolve_element_visibility (hb_svg_xml_parser_t &parser, + bool parent_visible) +{ + hb_svg_style_props_t style_props; + svg_parse_style_props (parser.find_attr ("style"), &style_props); + hb_svg_str_t display_str = svg_pick_attr_or_style (parser, style_props.display, "display"); + hb_svg_str_t visibility_str = svg_pick_attr_or_style (parser, style_props.visibility, "visibility"); + if (display_str.trim ().eq_ascii_ci ("none")) + return false; + hb_svg_str_t vis_trim = visibility_str.trim (); + if (!vis_trim.len || vis_trim.eq_ascii_ci ("inherit")) + return parent_visible; + if (vis_trim.eq_ascii_ci ("hidden") || + vis_trim.eq_ascii_ci ("collapse")) + return false; + if (vis_trim.eq_ascii_ci ("visible")) + return true; + return parent_visible; +} + +static void +svg_clip_collect_ref_element (hb_svg_clip_collect_context_t *ctx, + hb_svg_xml_parser_t &parser, + const hb_svg_transform_t &base_transform, + unsigned depth, + bool suppress_viewbox_once = false, + bool parent_visible = true, + bool allow_symbol_once = false); + +static void +svg_clip_collect_use_target (hb_svg_clip_collect_context_t *ctx, + hb_svg_xml_parser_t &use_parser, + const hb_svg_transform_t &base_transform, + unsigned depth) +{ + const unsigned SVG_MAX_CLIP_USE_DEPTH = 64; + if (depth >= SVG_MAX_CLIP_USE_DEPTH) + return; + + hb_svg_str_t href = hb_raster_svg_find_href_attr (use_parser); + hb_svg_str_t ref_id; + if (!hb_raster_svg_parse_local_id_ref (href, &ref_id, nullptr)) + return; + + const char *found = nullptr; + if (!hb_raster_svg_find_element_by_id (ctx->doc_start, ctx->doc_len, + ctx->svg_accel, ctx->doc_cache, + ref_id, &found)) + return; + + hb_decycler_node_t node (*ctx->use_decycler); + if (unlikely (!node.visit ((uintptr_t) found))) + return; + + hb_svg_transform_t effective = base_transform; + float use_x = 0.f, use_y = 0.f, use_w = 0.f, use_h = 0.f; + hb_raster_svg_parse_use_geometry (use_parser, &use_x, &use_y, &use_w, &use_h); + if (use_x != 0.f || use_y != 0.f) + { + hb_svg_transform_t tr; + tr.dx = use_x; + tr.dy = use_y; + effective.multiply (tr); + } + + unsigned remaining = ctx->doc_len - (unsigned) (found - ctx->doc_start); + hb_svg_xml_parser_t ref_parser (found, remaining); + hb_svg_token_type_t rt = ref_parser.next (); + if (rt != SVG_TOKEN_OPEN_TAG && rt != SVG_TOKEN_SELF_CLOSE_TAG) + return; + + bool viewport_mapped = false; + hb_svg_transform_t vb_t; + if (hb_raster_svg_compute_use_target_viewbox_transform (ref_parser, use_w, use_h, &vb_t)) + { + effective.multiply (vb_t); + viewport_mapped = true; + } + + bool allow_symbol = ref_parser.tag_name.eq ("symbol"); + svg_clip_collect_ref_element (ctx, ref_parser, effective, depth + 1, + viewport_mapped, true, allow_symbol); +} + +static void +svg_clip_collect_ref_element (hb_svg_clip_collect_context_t *ctx, + hb_svg_xml_parser_t &parser, + const hb_svg_transform_t &base_transform, + unsigned depth, + bool suppress_viewbox_once, + bool parent_visible, + bool allow_symbol_once) +{ + const unsigned SVG_MAX_CLIP_REF_DEPTH = 64; + if (depth >= SVG_MAX_CLIP_REF_DEPTH) + { + if (!parser.self_closing) + svg_skip_subtree (parser); + return; + } + + bool is_visible = svg_resolve_element_visibility (parser, parent_visible); + if (!is_visible) + { + if (!parser.self_closing) + svg_skip_subtree (parser); + return; + } + + /* Definitions are not directly renderable clip geometry. */ + if (parser.tag_name.eq ("defs")) + { + if (!parser.self_closing) + svg_skip_subtree (parser); + return; + } + if (parser.tag_name.eq ("symbol") && !allow_symbol_once) + { + if (!parser.self_closing) + svg_skip_subtree (parser); + return; + } + if (parser.tag_name.eq ("symbol")) + allow_symbol_once = false; + + hb_svg_transform_t effective = base_transform; + hb_svg_style_props_t geom_style_props; + svg_parse_style_props (parser.find_attr ("style"), &geom_style_props); + hb_svg_transform_t local_t; + if (svg_parse_element_transform (parser, &local_t)) + effective.multiply (local_t); + if (parser.tag_name.eq ("svg")) + { + float svg_x = hb_raster_svg_parse_non_percent_length (svg_pick_attr_or_style (parser, geom_style_props.x, "x")); + float svg_y = hb_raster_svg_parse_non_percent_length (svg_pick_attr_or_style (parser, geom_style_props.y, "y")); + if (svg_x != 0.f || svg_y != 0.f) + { + hb_svg_transform_t tr; + tr.dx = svg_x; + tr.dy = svg_y; + effective.multiply (tr); + } + + if (!suppress_viewbox_once) + { + float vb_x = 0.f, vb_y = 0.f, vb_w = 0.f, vb_h = 0.f; + if (hb_raster_svg_parse_viewbox (parser.find_attr ("viewBox"), + &vb_x, &vb_y, &vb_w, &vb_h)) + { + float viewport_w = hb_raster_svg_parse_non_percent_length (svg_pick_attr_or_style (parser, geom_style_props.width, "width")); + float viewport_h = hb_raster_svg_parse_non_percent_length (svg_pick_attr_or_style (parser, geom_style_props.height, "height")); + if (!(viewport_w > 0.f && viewport_h > 0.f)) + { + viewport_w = vb_w; + viewport_h = vb_h; + } + hb_svg_transform_t vb_t; + if (hb_raster_svg_compute_viewbox_transform (viewport_w, viewport_h, + vb_x, vb_y, vb_w, vb_h, + parser.find_attr ("preserveAspectRatio"), + &vb_t)) + effective.multiply (vb_t); + } + suppress_viewbox_once = false; + } + } + + hb_svg_shape_emit_data_t shape; + if (hb_raster_svg_parse_shape_tag (parser, &shape)) + { + svg_clip_append_shape (ctx, shape, effective); + if (!parser.self_closing) + svg_skip_subtree (parser); + return; + } + + if (parser.tag_name.eq ("use")) + { + svg_clip_collect_use_target (ctx, parser, effective, depth + 1); + if (!parser.self_closing) + svg_skip_subtree (parser); + return; + } + + bool is_container = hb_raster_svg_tag_is_container (parser.tag_name); + if (!is_container || parser.self_closing) + { + if (!parser.self_closing) + svg_skip_subtree (parser); + return; + } + + int inner_depth = 1; + while (inner_depth > 0) + { + hb_svg_token_type_t tok = parser.next (); + if (tok == SVG_TOKEN_EOF) break; + if (tok == SVG_TOKEN_CLOSE_TAG) + { + inner_depth--; + continue; + } + if (tok == SVG_TOKEN_OPEN_TAG || tok == SVG_TOKEN_SELF_CLOSE_TAG) + svg_clip_collect_ref_element (ctx, parser, effective, depth + 1, false, is_visible, false); + } +} + +void +hb_raster_svg_process_clip_path_def (hb_svg_defs_t *defs, + hb_svg_xml_parser_t &parser, + hb_svg_token_type_t tok, + const char *doc_start, + unsigned doc_len, + const OT::SVG::accelerator_t *svg_accel, + const OT::SVG::svg_doc_cache_t *doc_cache) +{ + hb_svg_clip_path_def_t clip; + hb_svg_str_t id = parser.find_attr ("id"); + hb_svg_str_t units = parser.find_attr ("clipPathUnits").trim (); + if (units.eq_ascii_ci ("objectBoundingBox")) + clip.units_user_space = false; + else if (units.eq_ascii_ci ("userSpaceOnUse")) + clip.units_user_space = true; + else + clip.units_user_space = true; + + hb_svg_transform_t cp_t; + if (svg_parse_element_transform (parser, &cp_t)) + { + clip.has_clip_transform = true; + clip.clip_transform = cp_t; + } + + clip.first_shape = defs->clip_shapes.length; + clip.shape_count = 0; + + if (tok == SVG_TOKEN_OPEN_TAG) + { + const unsigned SVG_MAX_CLIP_DEPTH = 64; + hb_svg_transform_t inherited[SVG_MAX_CLIP_DEPTH]; + bool inherited_visibility[SVG_MAX_CLIP_DEPTH]; + inherited[0] = hb_svg_transform_t (); + inherited[1] = hb_svg_transform_t (); + inherited_visibility[0] = true; + inherited_visibility[1] = true; + hb_decycler_t use_decycler; + + int cdepth = 1; + bool had_alloc_failure = false; + hb_svg_clip_collect_context_t collect_ctx = { + defs, &clip, + doc_start, doc_len, svg_accel, doc_cache, + &use_decycler, &had_alloc_failure + }; + while (cdepth > 0) + { + hb_svg_token_type_t ct = parser.next (); + if (ct == SVG_TOKEN_EOF) break; + if (ct == SVG_TOKEN_CLOSE_TAG) { cdepth--; continue; } + if (ct == SVG_TOKEN_OPEN_TAG || ct == SVG_TOKEN_SELF_CLOSE_TAG) + { + if (parser.tag_name.eq ("symbol")) + { + if (ct == SVG_TOKEN_OPEN_TAG) + { + int skip_depth = 1; + while (skip_depth > 0) + { + hb_svg_token_type_t st = parser.next (); + if (st == SVG_TOKEN_EOF) break; + if (st == SVG_TOKEN_CLOSE_TAG) skip_depth--; + else if (st == SVG_TOKEN_OPEN_TAG) skip_depth++; + } + } + continue; + } + + if (parser.tag_name.eq ("defs")) + { + if (ct == SVG_TOKEN_OPEN_TAG) + { + int skip_depth = 1; + while (skip_depth > 0) + { + hb_svg_token_type_t st = parser.next (); + if (st == SVG_TOKEN_EOF) break; + if (st == SVG_TOKEN_CLOSE_TAG) skip_depth--; + else if (st == SVG_TOKEN_OPEN_TAG) skip_depth++; + } + } + continue; + } + + bool parent_visible = (unsigned) cdepth < SVG_MAX_CLIP_DEPTH + ? inherited_visibility[cdepth] + : true; + bool is_visible = svg_resolve_element_visibility (parser, parent_visible); + bool is_hidden = !is_visible; + if (is_hidden) + { + if (ct == SVG_TOKEN_OPEN_TAG) + { + int skip_depth = 1; + while (skip_depth > 0) + { + hb_svg_token_type_t st = parser.next (); + if (st == SVG_TOKEN_EOF) break; + if (st == SVG_TOKEN_CLOSE_TAG) skip_depth--; + else if (st == SVG_TOKEN_OPEN_TAG) skip_depth++; + } + } + continue; + } + + hb_svg_transform_t effective = (unsigned) cdepth < SVG_MAX_CLIP_DEPTH + ? inherited[cdepth] + : hb_svg_transform_t (); + + hb_svg_transform_t local; + bool has_local_transform = svg_parse_element_transform (parser, &local); + if (has_local_transform) + { + effective.multiply (local); + } + + if (parser.tag_name.eq ("use")) + { + svg_clip_collect_use_target (&collect_ctx, parser, effective, 0); + } + else + { + hb_svg_shape_emit_data_t shape; + if (hb_raster_svg_parse_shape_tag (parser, &shape)) + svg_clip_append_shape (&collect_ctx, shape, effective); + } + + if (ct == SVG_TOKEN_OPEN_TAG) + { + if ((unsigned) (cdepth + 1) < SVG_MAX_CLIP_DEPTH) + { + inherited[cdepth + 1] = effective; + inherited_visibility[cdepth + 1] = is_visible; + } + cdepth++; + } + } + } + if (had_alloc_failure) + id = {}; + } + + if (id.len) + (void) defs->add_clip_path (hb_bytes_t (id.data, id.len), clip); +} + +struct hb_svg_clip_emit_data_t +{ + const hb_svg_defs_t *defs; + const hb_svg_clip_path_def_t *clip; + hb_transform_t<> base_transform; + hb_transform_t<> bbox_transform; + bool has_bbox_transform = false; +}; + +static inline hb_transform_t<> +svg_to_hb_transform (const hb_svg_transform_t &t) +{ + return hb_transform_t<> (t.xx, t.yx, t.xy, t.yy, t.dx, t.dy); +} + +static void +svg_clip_path_emit (hb_draw_funcs_t *dfuncs, + void *draw_data, + void *user_data) +{ + hb_raster_draw_t *rdr = (hb_raster_draw_t *) draw_data; + hb_svg_clip_emit_data_t *ed = (hb_svg_clip_emit_data_t *) user_data; + const hb_svg_clip_path_def_t *clip = ed->clip; + + for (unsigned i = 0; i < clip->shape_count; i++) + { + const hb_svg_clip_shape_t &s = ed->defs->clip_shapes[clip->first_shape + i]; + hb_transform_t<> t = ed->base_transform; + if (ed->has_bbox_transform) + t.multiply (ed->bbox_transform); + if (clip->has_clip_transform) + t.multiply (svg_to_hb_transform (clip->clip_transform)); + if (s.has_transform) + t.multiply (svg_to_hb_transform (s.transform)); + + hb_raster_draw_set_transform (rdr, t.xx, t.yx, t.xy, t.yy, t.x0, t.y0); + + hb_svg_shape_emit_data_t shape = s.shape; + hb_raster_svg_shape_path_emit (dfuncs, draw_data, &shape); + } +} + +bool +hb_raster_svg_push_clip_path_ref (hb_raster_paint_t *paint, + hb_svg_defs_t *defs, + hb_svg_str_t clip_path_str, + const hb_extents_t<> *object_bbox) +{ + if (clip_path_str.is_null ()) return false; + hb_svg_str_t trimmed = clip_path_str.trim (); + if (!trimmed.len || trimmed.eq_ascii_ci ("none")) return false; + + hb_svg_str_t clip_id; + if (!hb_raster_svg_parse_local_id_ref (trimmed, &clip_id, nullptr)) + return false; + + const hb_svg_clip_path_def_t *clip = defs->find_clip_path (hb_bytes_t (clip_id.data, clip_id.len)); + if (!clip) return false; + + hb_svg_clip_emit_data_t ed; + ed.defs = defs; + ed.clip = clip; + ed.base_transform = paint->current_effective_transform (); + + if (!clip->units_user_space) + { + if (!object_bbox || object_bbox->is_empty ()) + return false; + float w = object_bbox->xmax - object_bbox->xmin; + float h = object_bbox->ymax - object_bbox->ymin; + if (!(isfinite (w) && isfinite (h)) || w <= 0.f || h <= 0.f) + return false; + ed.has_bbox_transform = true; + ed.bbox_transform = hb_transform_t<> (w, 0, 0, h, object_bbox->xmin, object_bbox->ymin); + } + + hb_raster_paint_push_clip_path (paint, svg_clip_path_emit, &ed); + return true; +} diff --git a/src/hb-raster-svg-clip.hh b/src/hb-raster-svg-clip.hh new file mode 100644 index 000000000..0b89cc8f0 --- /dev/null +++ b/src/hb-raster-svg-clip.hh @@ -0,0 +1,53 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#ifndef HB_RASTER_SVG_CLIP_HH +#define HB_RASTER_SVG_CLIP_HH + +#include "hb.hh" + +#include "OT/Color/svg/svg.hh" +#include "hb-paint.hh" +#include "hb-raster-svg-defs.hh" + +struct hb_raster_paint_t; + +HB_INTERNAL void +hb_raster_svg_process_clip_path_def (hb_svg_defs_t *defs, + hb_svg_xml_parser_t &parser, + hb_svg_token_type_t tok, + const char *doc_start, + unsigned doc_len, + const OT::SVG::accelerator_t *svg_accel, + const OT::SVG::svg_doc_cache_t *doc_cache); + +HB_INTERNAL bool +hb_raster_svg_push_clip_path_ref (hb_raster_paint_t *paint, + hb_svg_defs_t *defs, + hb_svg_str_t clip_path_str, + const hb_extents_t<> *object_bbox); + +#endif /* HB_RASTER_SVG_CLIP_HH */ diff --git a/src/hb-raster-svg-color.cc b/src/hb-raster-svg-color.cc new file mode 100644 index 000000000..191d2106e --- /dev/null +++ b/src/hb-raster-svg-color.cc @@ -0,0 +1,336 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#include "hb.hh" + +#include "hb-raster-svg-color.hh" + +#include "hb-raster.h" +#include "hb-raster-svg-base.hh" +#include "hb-ot-color.h" + +#include +#include + +struct hb_svg_named_color_t +{ + const char *name; + uint32_t rgb; /* 0xRRGGBB */ +}; + +static const hb_svg_named_color_t svg_named_colors[] = { + {"aliceblue", 0xF0F8FF}, + {"antiquewhite", 0xFAEBD7}, + {"aqua", 0x00FFFF}, + {"aquamarine", 0x7FFFD4}, + {"azure", 0xF0FFFF}, + {"beige", 0xF5F5DC}, + {"bisque", 0xFFE4C4}, + {"black", 0x000000}, + {"blanchedalmond", 0xFFEBCD}, + {"blue", 0x0000FF}, + {"blueviolet", 0x8A2BE2}, + {"brown", 0xA52A2A}, + {"burlywood", 0xDEB887}, + {"cadetblue", 0x5F9EA0}, + {"chartreuse", 0x7FFF00}, + {"chocolate", 0xD2691E}, + {"coral", 0xFF7F50}, + {"cornflowerblue", 0x6495ED}, + {"cornsilk", 0xFFF8DC}, + {"crimson", 0xDC143C}, + {"cyan", 0x00FFFF}, + {"darkblue", 0x00008B}, + {"darkcyan", 0x008B8B}, + {"darkgoldenrod", 0xB8860B}, + {"darkgray", 0xA9A9A9}, + {"darkgreen", 0x006400}, + {"darkgrey", 0xA9A9A9}, + {"darkkhaki", 0xBDB76B}, + {"darkmagenta", 0x8B008B}, + {"darkolivegreen", 0x556B2F}, + {"darkorange", 0xFF8C00}, + {"darkorchid", 0x9932CC}, + {"darkred", 0x8B0000}, + {"darksalmon", 0xE9967A}, + {"darkseagreen", 0x8FBC8F}, + {"darkslateblue", 0x483D8B}, + {"darkslategray", 0x2F4F4F}, + {"darkslategrey", 0x2F4F4F}, + {"darkturquoise", 0x00CED1}, + {"darkviolet", 0x9400D3}, + {"deeppink", 0xFF1493}, + {"deepskyblue", 0x00BFFF}, + {"dimgray", 0x696969}, + {"dimgrey", 0x696969}, + {"dodgerblue", 0x1E90FF}, + {"firebrick", 0xB22222}, + {"floralwhite", 0xFFFAF0}, + {"forestgreen", 0x228B22}, + {"fuchsia", 0xFF00FF}, + {"gainsboro", 0xDCDCDC}, + {"ghostwhite", 0xF8F8FF}, + {"gold", 0xFFD700}, + {"goldenrod", 0xDAA520}, + {"gray", 0x808080}, + {"green", 0x008000}, + {"greenyellow", 0xADFF2F}, + {"grey", 0x808080}, + {"honeydew", 0xF0FFF0}, + {"hotpink", 0xFF69B4}, + {"indianred", 0xCD5C5C}, + {"indigo", 0x4B0082}, + {"ivory", 0xFFFFF0}, + {"khaki", 0xF0E68C}, + {"lavender", 0xE6E6FA}, + {"lavenderblush", 0xFFF0F5}, + {"lawngreen", 0x7CFC00}, + {"lemonchiffon", 0xFFFACD}, + {"lightblue", 0xADD8E6}, + {"lightcoral", 0xF08080}, + {"lightcyan", 0xE0FFFF}, + {"lightgoldenrodyellow", 0xFAFAD2}, + {"lightgray", 0xD3D3D3}, + {"lightgreen", 0x90EE90}, + {"lightgrey", 0xD3D3D3}, + {"lightpink", 0xFFB6C1}, + {"lightsalmon", 0xFFA07A}, + {"lightseagreen", 0x20B2AA}, + {"lightskyblue", 0x87CEFA}, + {"lightslategray", 0x778899}, + {"lightslategrey", 0x778899}, + {"lightsteelblue", 0xB0C4DE}, + {"lightyellow", 0xFFFFE0}, + {"lime", 0x00FF00}, + {"limegreen", 0x32CD32}, + {"linen", 0xFAF0E6}, + {"magenta", 0xFF00FF}, + {"maroon", 0x800000}, + {"mediumaquamarine", 0x66CDAA}, + {"mediumblue", 0x0000CD}, + {"mediumorchid", 0xBA55D3}, + {"mediumpurple", 0x9370DB}, + {"mediumseagreen", 0x3CB371}, + {"mediumslateblue", 0x7B68EE}, + {"mediumspringgreen", 0x00FA9A}, + {"mediumturquoise", 0x48D1CC}, + {"mediumvioletred", 0xC71585}, + {"midnightblue", 0x191970}, + {"mintcream", 0xF5FFFA}, + {"mistyrose", 0xFFE4E1}, + {"moccasin", 0xFFE4B5}, + {"navajowhite", 0xFFDEAD}, + {"navy", 0x000080}, + {"oldlace", 0xFDF5E6}, + {"olive", 0x808000}, + {"olivedrab", 0x6B8E23}, + {"orange", 0xFFA500}, + {"orangered", 0xFF4500}, + {"orchid", 0xDA70D6}, + {"palegoldenrod", 0xEEE8AA}, + {"palegreen", 0x98FB98}, + {"paleturquoise", 0xAFEEEE}, + {"palevioletred", 0xDB7093}, + {"papayawhip", 0xFFEFD5}, + {"peachpuff", 0xFFDAB9}, + {"peru", 0xCD853F}, + {"pink", 0xFFC0CB}, + {"plum", 0xDDA0DD}, + {"powderblue", 0xB0E0E6}, + {"purple", 0x800080}, + {"rebeccapurple", 0x663399}, + {"red", 0xFF0000}, + {"rosybrown", 0xBC8F8F}, + {"royalblue", 0x4169E1}, + {"saddlebrown", 0x8B4513}, + {"salmon", 0xFA8072}, + {"sandybrown", 0xF4A460}, + {"seagreen", 0x2E8B57}, + {"seashell", 0xFFF5EE}, + {"sienna", 0xA0522D}, + {"silver", 0xC0C0C0}, + {"skyblue", 0x87CEEB}, + {"slateblue", 0x6A5ACD}, + {"slategray", 0x708090}, + {"slategrey", 0x708090}, + {"snow", 0xFFFAFA}, + {"springgreen", 0x00FF7F}, + {"steelblue", 0x4682B4}, + {"tan", 0xD2B48C}, + {"teal", 0x008080}, + {"thistle", 0xD8BFD8}, + {"tomato", 0xFF6347}, + {"turquoise", 0x40E0D0}, + {"violet", 0xEE82EE}, + {"wheat", 0xF5DEB3}, + {"white", 0xFFFFFF}, + {"whitesmoke", 0xF5F5F5}, + {"yellow", 0xFFFF00}, + {"yellowgreen", 0x9ACD32}, +}; + +static int +hexval (char c) +{ + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; +} + +/* Parse SVG color value; returns HB_COLOR with alpha = 255. + * Sets *is_none if "none". */ +hb_color_t +hb_raster_svg_parse_color (hb_svg_str_t s, + hb_paint_funcs_t *pfuncs, + void *paint_data, + hb_color_t foreground, + hb_face_t *face, + unsigned palette, + bool *is_none) +{ + *is_none = false; + s = s.trim (); + if (!s.len) { *is_none = true; return HB_COLOR (0, 0, 0, 0); } + + if (s.eq_ascii_ci ("none") || s.eq_ascii_ci ("transparent")) + { + *is_none = true; + return HB_COLOR (0, 0, 0, 0); + } + + if (s.eq_ascii_ci ("currentColor")) + return foreground; + + /* var(--colorN) → CPAL palette color */ + if (s.starts_with_ascii_ci ("var(")) + { + const char *p = s.data + 4; + const char *e = s.data + s.len; + while (p < e && *p == ' ') p++; + if (p + 7 < e && p[0] == '-' && p[1] == '-' && p[2] == 'c' && + p[3] == 'o' && p[4] == 'l' && p[5] == 'o' && p[6] == 'r') + { + p += 7; + unsigned color_index = 0; + while (p < e && *p >= '0' && *p <= '9') + color_index = color_index * 10 + (*p++ - '0'); + + hb_color_t palette_color; + if (hb_paint_custom_palette_color (pfuncs, paint_data, color_index, &palette_color)) + return palette_color; + + unsigned count = 1; + hb_ot_color_palette_get_colors (face, palette, color_index, &count, &palette_color); + if (count) + return palette_color; + } + + /* Fallback value after comma: var(--colorN, fallback) */ + p = s.data + 4; + while (p < e && *p != ',') p++; + if (p < e) + { + p++; + while (p < e && *p == ' ') p++; + const char *val_start = p; + /* Find closing paren */ + while (e > val_start && *(e - 1) != ')') e--; + if (e > val_start) e--; + hb_svg_str_t fallback = {val_start, (unsigned) (e - val_start)}; + return hb_raster_svg_parse_color (fallback, pfuncs, paint_data, foreground, face, palette, is_none); + } + + return foreground; + } + + /* #RGB or #RRGGBB */ + if (s.data[0] == '#') + { + if (s.len == 4) /* #RGB */ + { + int r = hexval (s.data[1]); + int g = hexval (s.data[2]); + int b = hexval (s.data[3]); + if (r < 0 || g < 0 || b < 0) return HB_COLOR (0, 0, 0, 255); + return HB_COLOR (b * 17, g * 17, r * 17, 255); + } + if (s.len == 7) /* #RRGGBB */ + { + int r = hexval (s.data[1]) * 16 + hexval (s.data[2]); + int g = hexval (s.data[3]) * 16 + hexval (s.data[4]); + int b = hexval (s.data[5]) * 16 + hexval (s.data[6]); + return HB_COLOR (b, g, r, 255); + } + return HB_COLOR (0, 0, 0, 255); + } + + /* rgb(r, g, b) or rgb(r%, g%, b%) */ + if (s.starts_with ("rgb")) + { + const char *p = s.data + 3; + const char *e = s.data + s.len; + while (p < e && *p != '(') p++; + if (p < e) p++; + + auto read_component = [&] () -> int { + while (p < e && (*p == ' ' || *p == ',')) p++; + char buf[32]; + unsigned n = 0; + while (p < e && n < sizeof (buf) - 1 && ((*p >= '0' && *p <= '9') || *p == '.' || *p == '-')) + buf[n++] = *p++; + bool is_pct = (p < e && *p == '%'); + if (is_pct) p++; + buf[n] = '\0'; + float val = strtof (buf, nullptr); + if (is_pct) val = val * 255.f / 100.f; + return hb_clamp ((int) (val + 0.5f), 0, 255); + }; + + int r = read_component (); + int g = read_component (); + int b = read_component (); + return HB_COLOR (b, g, r, 255); + } + + /* Named colors (case-insensitive comparison) */ + { + char lower[32]; + unsigned n = hb_min (s.len, (unsigned) sizeof (lower) - 1); + for (unsigned i = 0; i < n; i++) + lower[i] = (s.data[i] >= 'A' && s.data[i] <= 'Z') ? s.data[i] + 32 : s.data[i]; + lower[n] = '\0'; + + for (unsigned i = 0; i < ARRAY_LENGTH (svg_named_colors); i++) + if (strcmp (lower, svg_named_colors[i].name) == 0) + { + uint32_t rgb = svg_named_colors[i].rgb; + return HB_COLOR (rgb & 0xFF, (rgb >> 8) & 0xFF, (rgb >> 16) & 0xFF, 255); + } + } + + return HB_COLOR (0, 0, 0, 255); +} diff --git a/src/hb-raster-svg-color.hh b/src/hb-raster-svg-color.hh new file mode 100644 index 000000000..893072e14 --- /dev/null +++ b/src/hb-raster-svg-color.hh @@ -0,0 +1,44 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#ifndef HB_RASTER_SVG_COLOR_HH +#define HB_RASTER_SVG_COLOR_HH + +#include "hb.hh" + +#include "hb-face.hh" +#include "hb-raster-svg-base.hh" + +HB_INTERNAL hb_color_t +hb_raster_svg_parse_color (hb_svg_str_t s, + hb_paint_funcs_t *pfuncs, + void *paint_data, + hb_color_t foreground, + hb_face_t *face, + unsigned palette, + bool *is_none); + +#endif /* HB_RASTER_SVG_COLOR_HH */ diff --git a/src/hb-raster-svg-context.hh b/src/hb-raster-svg-context.hh new file mode 100644 index 000000000..5882cab17 --- /dev/null +++ b/src/hb-raster-svg-context.hh @@ -0,0 +1,113 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#ifndef HB_RASTER_SVG_CONTEXT_HH +#define HB_RASTER_SVG_CONTEXT_HH + +#include "hb.hh" + +#include "OT/Color/svg/svg.hh" +#include "hb-decycler.hh" +#include "hb-raster-paint.hh" +#include "hb-raster-svg-base.hh" +#include "hb-raster-svg-defs.hh" + +struct hb_svg_fill_context_t +{ + hb_raster_paint_t *paint; + hb_paint_funcs_t *pfuncs; + hb_font_t *font; + unsigned palette; + hb_svg_defs_t *defs; +}; + +struct hb_svg_use_context_t +{ + hb_raster_paint_t *paint; + hb_paint_funcs_t *pfuncs; + + const char *doc_start; + unsigned doc_len; + const OT::SVG::accelerator_t *svg_accel; + const OT::SVG::svg_doc_cache_t *doc_cache; + hb_decycler_t *use_decycler; +}; + +struct hb_svg_render_context_t +{ + hb_raster_paint_t *paint; + hb_paint_funcs_t *pfuncs; + hb_font_t *font; + unsigned palette; + hb_color_t foreground; + hb_svg_defs_t defs; + int depth = 0; + + const char *doc_start; + unsigned doc_len; + const OT::SVG::accelerator_t *svg_accel = nullptr; + const OT::SVG::svg_doc_cache_t *doc_cache = nullptr; + hb_decycler_t use_decycler; + bool suppress_viewbox_once = false; + bool allow_symbol_render_once = false; + + void push_transform (float xx, float yx, float xy, float yy, float dx, float dy) + { + hb_paint_push_transform (pfuncs, paint, xx, yx, xy, yy, dx, dy); + } + void pop_transform () + { + hb_paint_pop_transform (pfuncs, paint); + } + void push_group () + { + hb_paint_push_group (pfuncs, paint); + } + void pop_group (hb_paint_composite_mode_t mode) + { + hb_paint_pop_group (pfuncs, paint, mode); + } + void paint_color (hb_color_t color) + { + hb_paint_color (pfuncs, paint, false, color); + } + void pop_clip () + { + hb_paint_pop_clip (pfuncs, paint); + } +}; + +struct hb_svg_cascade_t +{ + hb_svg_str_t fill; + float fill_opacity = 1.f; + hb_svg_str_t clip_path; + hb_color_t color = HB_COLOR (0, 0, 0, 255); + bool visibility = true; + float opacity = 1.f; +}; + +#endif /* HB_RASTER_SVG_CONTEXT_HH */ diff --git a/src/hb-raster-svg-defs-scan.cc b/src/hb-raster-svg-defs-scan.cc new file mode 100644 index 000000000..ba806b18f --- /dev/null +++ b/src/hb-raster-svg-defs-scan.cc @@ -0,0 +1,104 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#include "hb.hh" + +#include "hb-raster-svg-defs-scan.hh" + +#include "hb-raster-svg-clip.hh" +#include "hb-raster-svg-gradient.hh" + +static inline bool +hb_raster_svg_process_defs_child_tag (const hb_svg_defs_scan_context_t *ctx, + hb_svg_xml_parser_t &parser, + hb_svg_token_type_t tok) +{ + if (parser.tag_name.eq ("linearGradient")) + { + hb_raster_svg_process_gradient_def (ctx->defs, parser, tok, SVG_GRADIENT_LINEAR, + ctx->pfuncs, ctx->paint_data, + ctx->foreground, ctx->face, + ctx->palette); + return true; + } + if (parser.tag_name.eq ("radialGradient")) + { + hb_raster_svg_process_gradient_def (ctx->defs, parser, tok, SVG_GRADIENT_RADIAL, + ctx->pfuncs, ctx->paint_data, + ctx->foreground, ctx->face, + ctx->palette); + return true; + } + if (parser.tag_name.eq ("clipPath")) + { + hb_raster_svg_process_clip_path_def (ctx->defs, parser, tok, + ctx->doc_start, ctx->doc_len, + ctx->svg_accel, ctx->doc_cache); + return true; + } + return false; +} + +void +hb_raster_svg_process_defs_element (const hb_svg_defs_scan_context_t *ctx, + hb_svg_xml_parser_t &parser) +{ + int depth = 1; + + while (depth > 0) + { + hb_svg_token_type_t tok = parser.next (); + if (tok == SVG_TOKEN_EOF) break; + + if (tok == SVG_TOKEN_CLOSE_TAG) + { + depth--; + continue; + } + + if (tok == SVG_TOKEN_OPEN_TAG || tok == SVG_TOKEN_SELF_CLOSE_TAG) + { + if (!hb_raster_svg_process_defs_child_tag (ctx, parser, tok) && + tok == SVG_TOKEN_OPEN_TAG) + depth++; + } + } +} + +void +hb_raster_svg_collect_defs (const hb_svg_defs_scan_context_t *ctx, + const char *data, + unsigned data_len) +{ + hb_svg_xml_parser_t parser (data, data_len); + while (true) + { + hb_svg_token_type_t tok = parser.next (); + if (tok == SVG_TOKEN_EOF) break; + if (tok == SVG_TOKEN_OPEN_TAG || tok == SVG_TOKEN_SELF_CLOSE_TAG) + hb_raster_svg_process_defs_child_tag (ctx, parser, tok); + } +} diff --git a/src/hb-raster-svg-defs-scan.hh b/src/hb-raster-svg-defs-scan.hh new file mode 100644 index 000000000..bddad1f74 --- /dev/null +++ b/src/hb-raster-svg-defs-scan.hh @@ -0,0 +1,58 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#ifndef HB_RASTER_SVG_DEFS_SCAN_HH +#define HB_RASTER_SVG_DEFS_SCAN_HH + +#include "hb.hh" + +#include "OT/Color/svg/svg.hh" +#include "hb-raster-svg-defs.hh" + +struct hb_svg_defs_scan_context_t +{ + hb_svg_defs_t *defs; + hb_paint_funcs_t *pfuncs; + void *paint_data; + hb_color_t foreground; + hb_face_t *face; + unsigned palette; + const char *doc_start; + unsigned doc_len; + const OT::SVG::accelerator_t *svg_accel; + const OT::SVG::svg_doc_cache_t *doc_cache; +}; + +HB_INTERNAL void +hb_raster_svg_process_defs_element (const hb_svg_defs_scan_context_t *ctx, + hb_svg_xml_parser_t &parser); + +HB_INTERNAL void +hb_raster_svg_collect_defs (const hb_svg_defs_scan_context_t *ctx, + const char *data, + unsigned data_len); + +#endif /* HB_RASTER_SVG_DEFS_SCAN_HH */ diff --git a/src/hb-raster-svg-defs.cc b/src/hb-raster-svg-defs.cc new file mode 100644 index 000000000..1cce2f97f --- /dev/null +++ b/src/hb-raster-svg-defs.cc @@ -0,0 +1,117 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#include "hb.hh" + +#include "hb-raster-svg-defs.hh" + +#include + +hb_svg_defs_t::~hb_svg_defs_t () +{ + for (unsigned i = 0; i < owned_id_strings.length; i++) + hb_free (owned_id_strings.arrayZ[i]); +} + +bool +hb_svg_defs_t::add_id_mapping (hb_hashmap_t *map, + hb_bytes_t id, + unsigned idx) +{ + if (!id.length) + return false; + if (map->has (id)) + return true; + + unsigned n = (unsigned) id.length; + char *owned = (char *) hb_malloc (n + 1); + if (unlikely (!owned)) + return false; + hb_memcpy (owned, id.arrayZ, n); + owned[n] = '\0'; + if (unlikely (!owned_id_strings.push (owned))) + { + hb_free (owned); + return false; + } + + hb_bytes_t owned_key = hb_bytes_t (owned, n); + if (unlikely (!map->set (owned_key, idx))) + return false; + return true; +} + +bool +hb_svg_defs_t::add_gradient (hb_bytes_t id, const hb_svg_gradient_t &grad) +{ + unsigned idx = gradients.length; + gradients.push (grad); + if (unlikely (gradients.in_error ())) + return false; + + if (unlikely (!add_id_mapping (&gradient_by_id, id, idx))) + { + gradients.pop (); + return false; + } + return true; +} + +const hb_svg_gradient_t * +hb_svg_defs_t::find_gradient (hb_bytes_t id) const +{ + if (!id.length) return nullptr; + unsigned *idx = nullptr; + if (gradient_by_id.has (id, &idx)) + return &gradients[*idx]; + return nullptr; +} + +bool +hb_svg_defs_t::add_clip_path (hb_bytes_t id, const hb_svg_clip_path_def_t &clip) +{ + unsigned idx = clip_paths.length; + clip_paths.push (clip); + if (unlikely (clip_paths.in_error ())) + return false; + + if (unlikely (!add_id_mapping (&clip_path_by_id, id, idx))) + { + clip_paths.pop (); + return false; + } + return true; +} + +const hb_svg_clip_path_def_t * +hb_svg_defs_t::find_clip_path (hb_bytes_t id) const +{ + if (!id.length) return nullptr; + unsigned *idx = nullptr; + if (clip_path_by_id.has (id, &idx)) + return &clip_paths[*idx]; + return nullptr; +} diff --git a/src/hb-raster-svg-defs.hh b/src/hb-raster-svg-defs.hh new file mode 100644 index 000000000..ca1855658 --- /dev/null +++ b/src/hb-raster-svg-defs.hh @@ -0,0 +1,108 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#ifndef HB_RASTER_SVG_DEFS_HH +#define HB_RASTER_SVG_DEFS_HH + +#include "hb.hh" + +#include "hb-map.hh" +#include "hb-raster-svg-parse.hh" + +enum hb_svg_gradient_type_t +{ + SVG_GRADIENT_LINEAR, + SVG_GRADIENT_RADIAL +}; + +struct hb_svg_gradient_stop_t +{ + float offset; + hb_color_t color; + bool is_current_color = false; +}; + +struct hb_svg_gradient_t +{ + hb_svg_gradient_type_t type; + + hb_paint_extend_t spread = HB_PAINT_EXTEND_PAD; + bool has_spread = false; + hb_svg_transform_t gradient_transform; + bool has_gradient_transform = false; + bool units_user_space = false; + bool has_units_user_space = false; + + float x1 = 0, y1 = 0, x2 = 1, y2 = 0; + bool has_x1 = false, has_y1 = false, has_x2 = false, has_y2 = false; + + float cx = 0.5f, cy = 0.5f, r = 0.5f; + float fx = -1.f, fy = -1.f, fr = 0.f; + bool has_cx = false, has_cy = false, has_r = false; + bool has_fx = false, has_fy = false, has_fr = false; + + hb_vector_t stops; + + hb_bytes_t href_id = {}; +}; + +struct hb_svg_clip_path_def_t +{ + unsigned first_shape = 0; + unsigned shape_count = 0; + hb_svg_transform_t clip_transform; + bool has_clip_transform = false; + bool units_user_space = true; +}; + +struct hb_svg_clip_shape_t +{ + hb_svg_shape_emit_data_t shape; + hb_svg_transform_t transform; + bool has_transform = false; +}; + +struct hb_svg_defs_t +{ + hb_vector_t gradients; + hb_vector_t clip_shapes; + hb_vector_t clip_paths; + hb_hashmap_t gradient_by_id; + hb_hashmap_t clip_path_by_id; + hb_vector_t owned_id_strings; + + ~hb_svg_defs_t (); + + bool add_id_mapping (hb_hashmap_t *map, + hb_bytes_t id, + unsigned idx); + bool add_gradient (hb_bytes_t id, const hb_svg_gradient_t &grad); + const hb_svg_gradient_t *find_gradient (hb_bytes_t id) const; + bool add_clip_path (hb_bytes_t id, const hb_svg_clip_path_def_t &clip); + const hb_svg_clip_path_def_t *find_clip_path (hb_bytes_t id) const; +}; + +#endif /* HB_RASTER_SVG_DEFS_HH */ diff --git a/src/hb-raster-svg-fill.cc b/src/hb-raster-svg-fill.cc new file mode 100644 index 000000000..2c9af7450 --- /dev/null +++ b/src/hb-raster-svg-fill.cc @@ -0,0 +1,292 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#include "hb.hh" + +#include "hb-raster-svg-fill.hh" + +#include "hb-raster-svg-base.hh" +#include "hb-raster-svg-color.hh" +#include "hb-decycler.hh" + +#include + +struct hb_svg_color_line_data_t +{ + const hb_svg_gradient_t *grad; + hb_paint_extend_t extend; + float alpha_scale; + hb_color_t current_color; +}; + +static unsigned +svg_color_line_get_stops (hb_color_line_t *color_line HB_UNUSED, + void *color_line_data, + unsigned int start, + unsigned int *count, + hb_color_stop_t *color_stops, + void *user_data HB_UNUSED) +{ + hb_svg_color_line_data_t *cl = (hb_svg_color_line_data_t *) color_line_data; + const hb_svg_gradient_t *grad = cl->grad; + unsigned total = grad->stops.length; + + if (count) + { + unsigned n = hb_min (*count, total > start ? total - start : 0u); + for (unsigned i = 0; i < n; i++) + { + const hb_svg_gradient_stop_t &stop = grad->stops[start + i]; + color_stops[i].offset = stop.offset; + color_stops[i].is_foreground = false; + hb_color_t c = stop.is_current_color ? cl->current_color : stop.color; + if (stop.is_current_color) + { + uint8_t a = (uint8_t) hb_raster_div255 (hb_color_get_alpha (c) * hb_color_get_alpha (stop.color)); + c = HB_COLOR (hb_color_get_blue (c), + hb_color_get_green (c), + hb_color_get_red (c), + a); + } + if (cl->alpha_scale < 1.f) + { + uint8_t a = (uint8_t) hb_clamp ((int) (hb_color_get_alpha (c) * cl->alpha_scale + 0.5f), 0, 255); + c = HB_COLOR (hb_color_get_blue (c), + hb_color_get_green (c), + hb_color_get_red (c), + a); + } + color_stops[i].color = c; + } + *count = n; + } + return total; +} + +static hb_paint_extend_t +svg_color_line_get_extend (hb_color_line_t *color_line HB_UNUSED, + void *color_line_data, + void *user_data HB_UNUSED) +{ + hb_svg_color_line_data_t *cl = (hb_svg_color_line_data_t *) color_line_data; + return cl->extend; +} + +static bool +svg_parse_paint_url_with_fallback (hb_svg_str_t s, + hb_svg_str_t *out_id, + hb_svg_str_t *fallback) +{ + if (out_id) *out_id = {}; + hb_svg_str_t id; + if (!hb_raster_svg_parse_local_id_ref (s, &id, fallback)) + return false; + if (!s.trim ().starts_with_ascii_ci ("url(")) + return false; + if (out_id) *out_id = id; + return id.len > 0; +} + +void +hb_raster_svg_emit_fill (const hb_svg_fill_context_t *ctx, + hb_svg_str_t fill_str, + float fill_opacity, + const hb_extents_t<> *object_bbox, + hb_color_t current_color) +{ + bool is_none = false; + + hb_svg_str_t url_id; + hb_svg_str_t fallback_paint; + bool has_url_paint = svg_parse_paint_url_with_fallback (fill_str, &url_id, &fallback_paint); + + const hb_svg_gradient_t *grad = has_url_paint ? ctx->defs->find_gradient (hb_bytes_t (url_id.data, url_id.len)) : nullptr; + if (has_url_paint && !grad) + { + if (fallback_paint.len) + hb_raster_svg_emit_fill (ctx, fallback_paint, fill_opacity, object_bbox, current_color); + return; + } + if (grad) + { + const unsigned SVG_MAX_GRADIENT_REF_DEPTH = 1024; + hb_vector_t chain; + hb_decycler_t decycler; + const hb_svg_gradient_t *cur = grad; + while (cur) + { + if (chain.length >= SVG_MAX_GRADIENT_REF_DEPTH) + break; + + hb_decycler_node_t node (decycler); + if (unlikely (!node.visit ((uintptr_t) cur))) + break; + + chain.push (cur); + if (unlikely (chain.in_error ())) + { + if (fallback_paint.len) + hb_raster_svg_emit_fill (ctx, fallback_paint, fill_opacity, object_bbox, current_color); + return; + } + + if (!cur->href_id.length) break; + const hb_svg_gradient_t *next = ctx->defs->find_gradient (cur->href_id); + if (!next) break; + cur = next; + } + if (!chain.length) + { + if (fallback_paint.len) + hb_raster_svg_emit_fill (ctx, fallback_paint, fill_opacity, object_bbox, current_color); + return; + } + + hb_svg_gradient_t effective = *chain.arrayZ[chain.length - 1]; + for (int i = (int) chain.length - 2; i >= 0; i--) + { + const hb_svg_gradient_t *g = chain.arrayZ[i]; + effective.type = g->type; + if (g->stops.length) effective.stops = g->stops; + if (g->has_spread) { effective.spread = g->spread; effective.has_spread = true; } + if (g->has_units_user_space) + { + effective.units_user_space = g->units_user_space; + effective.has_units_user_space = true; + } + if (g->has_gradient_transform) + { + effective.gradient_transform = g->gradient_transform; + effective.has_gradient_transform = true; + } + if (g->has_x1) { effective.x1 = g->x1; effective.has_x1 = true; } + if (g->has_y1) { effective.y1 = g->y1; effective.has_y1 = true; } + if (g->has_x2) { effective.x2 = g->x2; effective.has_x2 = true; } + if (g->has_y2) { effective.y2 = g->y2; effective.has_y2 = true; } + if (g->has_cx) { effective.cx = g->cx; effective.has_cx = true; } + if (g->has_cy) { effective.cy = g->cy; effective.has_cy = true; } + if (g->has_r) { effective.r = g->r; effective.has_r = true; } + if (g->has_fx) { effective.fx = g->fx; effective.has_fx = true; } + if (g->has_fy) { effective.fy = g->fy; effective.has_fy = true; } + if (g->has_fr) { effective.fr = g->fr; effective.has_fr = true; } + } + if (!effective.stops.length) + { + if (fallback_paint.len) + hb_raster_svg_emit_fill (ctx, fallback_paint, fill_opacity, object_bbox, current_color); + return; + } + + hb_svg_color_line_data_t cl_data; + cl_data.grad = &effective; + cl_data.extend = effective.spread; + cl_data.alpha_scale = hb_clamp (fill_opacity, 0.f, 1.f); + cl_data.current_color = current_color; + + hb_color_line_t cl = { + &cl_data, + svg_color_line_get_stops, nullptr, + svg_color_line_get_extend, nullptr + }; + + bool has_bbox_transform = !effective.units_user_space && object_bbox && !object_bbox->is_empty (); + if (has_bbox_transform) + { + float w = object_bbox->xmax - object_bbox->xmin; + float h = object_bbox->ymax - object_bbox->ymin; + if (isfinite (w) && isfinite (h) && w > 0.f && h > 0.f) + hb_paint_push_transform (ctx->pfuncs, ctx->paint, w, 0, 0, h, object_bbox->xmin, object_bbox->ymin); + else + has_bbox_transform = false; + } + + if (effective.has_gradient_transform) + hb_paint_push_transform (ctx->pfuncs, ctx->paint, + effective.gradient_transform.xx, + effective.gradient_transform.yx, + effective.gradient_transform.xy, + effective.gradient_transform.yy, + effective.gradient_transform.dx, + effective.gradient_transform.dy); + + if (effective.type == SVG_GRADIENT_LINEAR) + { + hb_paint_linear_gradient (ctx->pfuncs, ctx->paint, &cl, + effective.x1, effective.y1, + effective.x2, effective.y2, + effective.x2 - (effective.y2 - effective.y1), + effective.y2 + (effective.x2 - effective.x1)); + } + else + { + if (!isfinite (effective.r) || effective.r < 0.f) + { + if (effective.has_gradient_transform) + hb_paint_pop_transform (ctx->pfuncs, ctx->paint); + if (has_bbox_transform) + hb_paint_pop_transform (ctx->pfuncs, ctx->paint); + if (fallback_paint.len) + hb_raster_svg_emit_fill (ctx, fallback_paint, fill_opacity, object_bbox, current_color); + return; + } + + float fx = effective.has_fx ? effective.fx : effective.cx; + float fy = effective.has_fy ? effective.fy : effective.cy; + float fr = effective.has_fr ? effective.fr : 0.f; + if (!isfinite (fr) || fr < 0.f) + fr = 0.f; + fr = hb_min (fr, effective.r); + + hb_paint_radial_gradient (ctx->pfuncs, ctx->paint, &cl, + fx, fy, fr, + effective.cx, effective.cy, effective.r); + } + + if (effective.has_gradient_transform) + hb_paint_pop_transform (ctx->pfuncs, ctx->paint); + if (has_bbox_transform) + hb_paint_pop_transform (ctx->pfuncs, ctx->paint); + + return; + } + + hb_color_t color = hb_raster_svg_parse_color (fill_str, + ctx->pfuncs, + ctx->paint, + current_color, + hb_font_get_face (ctx->font), + ctx->palette, + &is_none); + if (is_none) return; + + if (fill_opacity < 1.f) + color = HB_COLOR (hb_color_get_blue (color), + hb_color_get_green (color), + hb_color_get_red (color), + (uint8_t) (hb_color_get_alpha (color) * fill_opacity + 0.5f)); + + hb_paint_color (ctx->pfuncs, ctx->paint, false, color); +} diff --git a/src/hb-raster-svg-fill.hh b/src/hb-raster-svg-fill.hh new file mode 100644 index 000000000..ce4ceecd9 --- /dev/null +++ b/src/hb-raster-svg-fill.hh @@ -0,0 +1,41 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#ifndef HB_RASTER_SVG_FILL_HH +#define HB_RASTER_SVG_FILL_HH + +#include "hb.hh" + +#include "hb-raster-svg-context.hh" + +HB_INTERNAL void +hb_raster_svg_emit_fill (const hb_svg_fill_context_t *ctx, + hb_svg_str_t fill_str, + float fill_opacity, + const hb_extents_t<> *object_bbox, + hb_color_t current_color); + +#endif /* HB_RASTER_SVG_FILL_HH */ diff --git a/src/hb-raster-svg-gradient.cc b/src/hb-raster-svg-gradient.cc new file mode 100644 index 000000000..81c2562b6 --- /dev/null +++ b/src/hb-raster-svg-gradient.cc @@ -0,0 +1,242 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#include "hb.hh" + +#include "hb-raster-svg-gradient.hh" + +#include "hb-raster-svg-base.hh" + +static bool +svg_parse_gradient_stop (hb_svg_xml_parser_t &parser, + hb_svg_gradient_t &grad, + hb_paint_funcs_t *pfuncs, + void *paint_data, + hb_color_t foreground, + hb_face_t *face, + unsigned palette) +{ + const unsigned SVG_MAX_GRADIENT_STOPS = 1024; + if (grad.stops.length >= SVG_MAX_GRADIENT_STOPS) + return true; + + hb_svg_attr_view_t attrs (parser); + hb_svg_str_t style = attrs.get ("style"); + hb_svg_style_props_t style_props; + svg_parse_style_props (style, &style_props); + hb_svg_str_t offset_str = svg_pick_attr_or_style (parser, style_props.offset, "offset"); + hb_svg_str_t color_str = svg_pick_attr_or_style (parser, style_props.stop_color, "stop-color"); + hb_svg_str_t opacity_str = svg_pick_attr_or_style (parser, style_props.stop_opacity, "stop-opacity"); + hb_svg_str_t display_str = svg_pick_attr_or_style (parser, style_props.display, "display"); + hb_svg_str_t visibility_str = svg_pick_attr_or_style (parser, style_props.visibility, "visibility"); + + if (display_str.trim ().eq_ascii_ci ("none")) + return true; + hb_svg_str_t visibility_trim = visibility_str.trim (); + if (visibility_trim.eq_ascii_ci ("hidden") || + visibility_trim.eq_ascii_ci ("collapse")) + return true; + + float offset = 0; + if (offset_str.len) + offset = hb_clamp (svg_parse_number_or_percent (offset_str, nullptr), 0.f, 1.f); + if (grad.stops.length) + offset = hb_max (offset, grad.stops.arrayZ[grad.stops.length - 1].offset); + + bool is_none = false; + hb_color_t color = HB_COLOR (0, 0, 0, 255); + bool is_current_color = false; + if (color_str.len && !svg_str_is_inherit (color_str)) + { + is_current_color = color_str.trim ().eq_ascii_ci ("currentColor"); + color = hb_raster_svg_parse_color (color_str, pfuncs, paint_data, foreground, face, palette, &is_none); + } + + if (opacity_str.len && !svg_str_is_inherit (opacity_str)) + { + float opacity = svg_parse_float_clamped01 (opacity_str); + color = HB_COLOR (hb_color_get_blue (color), + hb_color_get_green (color), + hb_color_get_red (color), + (uint8_t) (hb_color_get_alpha (color) * opacity + 0.5f)); + } + + hb_svg_gradient_stop_t stop; + stop.offset = offset; + stop.color = color; + stop.is_current_color = is_current_color; + grad.stops.push (stop); + return !grad.stops.in_error (); +} + +static void +svg_parse_gradient_attrs (hb_svg_xml_parser_t &parser, + hb_svg_gradient_t &grad) +{ + hb_svg_style_props_t style_props; + svg_parse_style_props (parser.find_attr ("style"), &style_props); + + hb_svg_str_t spread_str = svg_pick_attr_or_style (parser, style_props.spread_method, "spreadMethod").trim (); + if (spread_str.eq_ascii_ci ("reflect")) + { + grad.spread = HB_PAINT_EXTEND_REFLECT; + grad.has_spread = true; + } + else if (spread_str.eq_ascii_ci ("repeat")) + { + grad.spread = HB_PAINT_EXTEND_REPEAT; + grad.has_spread = true; + } + else if (spread_str.eq_ascii_ci ("pad")) + { + grad.spread = HB_PAINT_EXTEND_PAD; + grad.has_spread = true; + } + + hb_svg_str_t units_str = svg_pick_attr_or_style (parser, style_props.gradient_units, "gradientUnits").trim (); + if (units_str.eq_ascii_ci ("userSpaceOnUse")) + { + grad.units_user_space = true; + grad.has_units_user_space = true; + } + else if (units_str.eq_ascii_ci ("objectBoundingBox")) + { + grad.units_user_space = false; + grad.has_units_user_space = true; + } + + hb_svg_str_t transform_str = svg_pick_attr_or_style (parser, style_props.gradient_transform, "gradientTransform"); + if (transform_str.len) + { + grad.has_gradient_transform = true; + hb_raster_svg_parse_transform (transform_str, &grad.gradient_transform); + } + + hb_svg_str_t href = hb_raster_svg_find_href_attr (parser); + if (href.len) + { + hb_svg_str_t href_id; + if (hb_raster_svg_parse_local_id_ref (href, &href_id, nullptr)) + grad.href_id = hb_bytes_t (href_id.data, href_id.len); + } +} + +static void +svg_parse_gradient_geometry_attrs (hb_svg_xml_parser_t &parser, + hb_svg_gradient_t &grad) +{ + hb_svg_style_props_t style_props; + svg_parse_style_props (parser.find_attr ("style"), &style_props); + if (grad.type == SVG_GRADIENT_LINEAR) + { + hb_svg_str_t x1_str = svg_pick_attr_or_style (parser, style_props.x1, "x1"); + hb_svg_str_t y1_str = svg_pick_attr_or_style (parser, style_props.y1, "y1"); + hb_svg_str_t x2_str = svg_pick_attr_or_style (parser, style_props.x2, "x2"); + hb_svg_str_t y2_str = svg_pick_attr_or_style (parser, style_props.y2, "y2"); + if (x1_str.len) { grad.x1 = svg_parse_number_or_percent (x1_str, nullptr); grad.has_x1 = true; } + if (y1_str.len) { grad.y1 = svg_parse_number_or_percent (y1_str, nullptr); grad.has_y1 = true; } + if (x2_str.len) { grad.x2 = svg_parse_number_or_percent (x2_str, nullptr); grad.has_x2 = true; } + if (y2_str.len) { grad.y2 = svg_parse_number_or_percent (y2_str, nullptr); grad.has_y2 = true; } + + if (!grad.has_x2) + grad.x2 = 1.f; + } + else + { + hb_svg_str_t cx_str = svg_pick_attr_or_style (parser, style_props.cx, "cx"); + hb_svg_str_t cy_str = svg_pick_attr_or_style (parser, style_props.cy, "cy"); + hb_svg_str_t r_str = svg_pick_attr_or_style (parser, style_props.r, "r"); + hb_svg_str_t fx_str = svg_pick_attr_or_style (parser, style_props.fx, "fx"); + hb_svg_str_t fy_str = svg_pick_attr_or_style (parser, style_props.fy, "fy"); + hb_svg_str_t fr_str = svg_pick_attr_or_style (parser, style_props.fr, "fr"); + + if (cx_str.len) { grad.cx = svg_parse_number_or_percent (cx_str, nullptr); grad.has_cx = true; } + if (cy_str.len) { grad.cy = svg_parse_number_or_percent (cy_str, nullptr); grad.has_cy = true; } + if (r_str.len) { grad.r = svg_parse_number_or_percent (r_str, nullptr); grad.has_r = true; } + if (fx_str.len) { grad.fx = svg_parse_number_or_percent (fx_str, nullptr); grad.has_fx = true; } + if (fy_str.len) { grad.fy = svg_parse_number_or_percent (fy_str, nullptr); grad.has_fy = true; } + if (fr_str.len) { grad.fr = svg_parse_number_or_percent (fr_str, nullptr); grad.has_fr = true; } + } +} + +static void +svg_parse_gradient_children (hb_svg_defs_t *defs, + hb_svg_xml_parser_t &parser, + hb_svg_gradient_t &grad, + hb_svg_str_t *id, + hb_paint_funcs_t *pfuncs, + void *paint_data, + hb_color_t foreground, + hb_face_t *face, + unsigned palette) +{ + int gdepth = 1; + bool had_alloc_failure = false; + while (gdepth > 0) + { + hb_svg_token_type_t gt = parser.next (); + if (gt == SVG_TOKEN_EOF) break; + if (gt == SVG_TOKEN_CLOSE_TAG) { gdepth--; continue; } + if ((gt == SVG_TOKEN_OPEN_TAG || gt == SVG_TOKEN_SELF_CLOSE_TAG) && + parser.tag_name.eq ("stop")) + if (unlikely (!svg_parse_gradient_stop (parser, grad, + pfuncs, paint_data, + foreground, face, + palette))) + had_alloc_failure = true; + if (gt == SVG_TOKEN_OPEN_TAG && !parser.tag_name.eq ("stop")) + gdepth++; + } + if (had_alloc_failure || defs->gradients.in_error ()) + *id = {}; +} + +void +hb_raster_svg_process_gradient_def (hb_svg_defs_t *defs, + hb_svg_xml_parser_t &parser, + hb_svg_token_type_t tok, + hb_svg_gradient_type_t type, + hb_paint_funcs_t *pfuncs, + void *paint_data, + hb_color_t foreground, + hb_face_t *face, + unsigned palette) +{ + hb_svg_gradient_t grad; + grad.type = type; + svg_parse_gradient_geometry_attrs (parser, grad); + svg_parse_gradient_attrs (parser, grad); + + hb_svg_str_t id = parser.find_attr ("id"); + if (tok == SVG_TOKEN_OPEN_TAG) + svg_parse_gradient_children (defs, parser, grad, &id, + pfuncs, paint_data, + foreground, face, + palette); + + if (id.len) + (void) defs->add_gradient (hb_bytes_t (id.data, id.len), grad); +} diff --git a/src/hb-raster-svg-gradient.hh b/src/hb-raster-svg-gradient.hh new file mode 100644 index 000000000..0b1e6fd0c --- /dev/null +++ b/src/hb-raster-svg-gradient.hh @@ -0,0 +1,46 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#ifndef HB_RASTER_SVG_GRADIENT_HH +#define HB_RASTER_SVG_GRADIENT_HH + +#include "hb.hh" + +#include "hb-raster-svg-color.hh" +#include "hb-raster-svg-defs.hh" + +HB_INTERNAL void +hb_raster_svg_process_gradient_def (hb_svg_defs_t *defs, + hb_svg_xml_parser_t &parser, + hb_svg_token_type_t tok, + hb_svg_gradient_type_t type, + hb_paint_funcs_t *pfuncs, + void *paint_data, + hb_color_t foreground, + hb_face_t *face, + unsigned palette); + +#endif /* HB_RASTER_SVG_GRADIENT_HH */ diff --git a/src/hb-raster-svg-parse.cc b/src/hb-raster-svg-parse.cc new file mode 100644 index 000000000..de8b5ceae --- /dev/null +++ b/src/hb-raster-svg-parse.cc @@ -0,0 +1,661 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#include "hb.hh" + +#include "hb-raster-svg-parse.hh" + +#include +bool +hb_raster_svg_parse_transform (hb_svg_str_t s, hb_svg_transform_t *out) +{ + hb_svg_float_parser_t fp (s); + + while (fp.p < fp.end) + { + fp.skip_ws_comma (); + if (fp.p >= fp.end) break; + + const char *start = fp.p; + while (fp.p < fp.end && *fp.p != '(') fp.p++; + hb_svg_str_t func_name = {start, (unsigned) (fp.p - start)}; + + while (func_name.len && (func_name.data[func_name.len - 1] == ' ' || + func_name.data[func_name.len - 1] == '\t')) + func_name.len--; + + if (fp.p >= fp.end) break; + fp.p++; + + hb_svg_transform_t t; + + if (func_name.eq_ascii_ci ("matrix")) + { + t.xx = fp.next_float (); + t.yx = fp.next_float (); + t.xy = fp.next_float (); + t.yy = fp.next_float (); + t.dx = fp.next_float (); + t.dy = fp.next_float (); + } + else if (func_name.eq_ascii_ci ("translate")) + { + t.dx = fp.next_float (); + fp.skip_ws_comma (); + if (fp.p < fp.end && *fp.p != ')') + t.dy = fp.next_float (); + } + else if (func_name.eq_ascii_ci ("scale")) + { + t.xx = fp.next_float (); + fp.skip_ws_comma (); + if (fp.p < fp.end && *fp.p != ')') + t.yy = fp.next_float (); + else + t.yy = t.xx; + } + else if (func_name.eq_ascii_ci ("rotate")) + { + float angle = fp.next_float () * (float) M_PI / 180.f; + float cs = cosf (angle), sn = sinf (angle); + fp.skip_ws_comma (); + if (fp.p < fp.end && *fp.p != ')') + { + float cx = fp.next_float (); + float cy = fp.next_float (); + t.xx = cs; t.yx = sn; + t.xy = -sn; t.yy = cs; + t.dx = cx - cs * cx + sn * cy; + t.dy = cy - sn * cx - cs * cy; + } + else + { + t.xx = cs; t.yx = sn; + t.xy = -sn; t.yy = cs; + } + } + else if (func_name.eq_ascii_ci ("skewX")) + { + float angle = fp.next_float () * (float) M_PI / 180.f; + t.xy = tanf (angle); + } + else if (func_name.eq_ascii_ci ("skewY")) + { + float angle = fp.next_float () * (float) M_PI / 180.f; + t.yx = tanf (angle); + } + + while (fp.p < fp.end && *fp.p != ')') fp.p++; + if (fp.p < fp.end) fp.p++; + + out->multiply (t); + } + return true; +} + +static void +svg_arc_to_cubics (hb_draw_funcs_t *dfuncs, void *draw_data, hb_draw_state_t *st, + float cx, float cy, + float rx, float ry, + float phi, float theta1, float dtheta) +{ + int n_segs = (int) ceilf (fabsf (dtheta) / ((float) M_PI / 2.f)); + if (n_segs < 1) n_segs = 1; + float seg_angle = dtheta / n_segs; + + float cos_phi = cosf (phi); + float sin_phi = sinf (phi); + + for (int i = 0; i < n_segs; i++) + { + float t1 = theta1 + i * seg_angle; + float t2 = t1 + seg_angle; + float alpha = sinf (seg_angle) * + (sqrtf (4.f + 3.f * tanf (seg_angle / 2.f) * tanf (seg_angle / 2.f)) - 1.f) / 3.f; + + float cos_t1 = cosf (t1), sin_t1 = sinf (t1); + float cos_t2 = cosf (t2), sin_t2 = sinf (t2); + + float e1x = rx * cos_t1, e1y = ry * sin_t1; + float e2x = rx * cos_t2, e2y = ry * sin_t2; + float d1x = -rx * sin_t1, d1y = ry * cos_t1; + float d2x = -rx * sin_t2, d2y = ry * cos_t2; + + float cp1x = e1x + alpha * d1x; + float cp1y = e1y + alpha * d1y; + float cp2x = e2x - alpha * d2x; + float cp2y = e2y - alpha * d2y; + + float r_cp1x = cos_phi * cp1x - sin_phi * cp1y + cx; + float r_cp1y = sin_phi * cp1x + cos_phi * cp1y + cy; + float r_cp2x = cos_phi * cp2x - sin_phi * cp2y + cx; + float r_cp2y = sin_phi * cp2x + cos_phi * cp2y + cy; + float r_e2x = cos_phi * e2x - sin_phi * e2y + cx; + float r_e2y = sin_phi * e2x + cos_phi * e2y + cy; + + hb_draw_cubic_to (dfuncs, draw_data, st, + r_cp1x, r_cp1y, + r_cp2x, r_cp2y, + r_e2x, r_e2y); + } +} + +static void +svg_arc_endpoint_to_center (float x1, float y1, float x2, float y2, + float rx, float ry, float phi_deg, + bool large_arc, bool sweep, + float *cx_out, float *cy_out, + float *theta1_out, float *dtheta_out, + float *rx_out, float *ry_out) +{ + float phi = phi_deg * (float) M_PI / 180.f; + float cos_phi = cosf (phi), sin_phi = sinf (phi); + + float mx = (x1 - x2) / 2.f; + float my = (y1 - y2) / 2.f; + float x1p = cos_phi * mx + sin_phi * my; + float y1p = -sin_phi * mx + cos_phi * my; + + rx = fabsf (rx); ry = fabsf (ry); + if (rx < 1e-10f || ry < 1e-10f) + { + *cx_out = (x1 + x2) / 2.f; + *cy_out = (y1 + y2) / 2.f; + *theta1_out = 0; + *dtheta_out = 0; + *rx_out = rx; *ry_out = ry; + return; + } + + float x1p2 = x1p * x1p, y1p2 = y1p * y1p; + float rx2 = rx * rx, ry2 = ry * ry; + float lambda = x1p2 / rx2 + y1p2 / ry2; + if (lambda > 1.f) + { + float sl = sqrtf (lambda); + rx *= sl; ry *= sl; + rx2 = rx * rx; ry2 = ry * ry; + } + + float num = rx2 * ry2 - rx2 * y1p2 - ry2 * x1p2; + float den = rx2 * y1p2 + ry2 * x1p2; + float sq = (den > 0.f) ? sqrtf (hb_max (num / den, 0.f)) : 0.f; + if (large_arc == sweep) sq = -sq; + + float cxp = sq * rx * y1p / ry; + float cyp = -sq * ry * x1p / rx; + + float cx = cos_phi * cxp - sin_phi * cyp + (x1 + x2) / 2.f; + float cy = sin_phi * cxp + cos_phi * cyp + (y1 + y2) / 2.f; + + auto angle = [] (float ux, float uy, float vx, float vy) -> float { + float dot = ux * vx + uy * vy; + float len = sqrtf ((ux * ux + uy * uy) * (vx * vx + vy * vy)); + if (!(len > 0.f) || !isfinite (len)) + return 0.f; + float a = acosf (hb_clamp (dot / len, -1.f, 1.f)); + if (ux * vy - uy * vx < 0.f) a = -a; + return a; + }; + + float theta1 = angle (1.f, 0.f, (x1p - cxp) / rx, (y1p - cyp) / ry); + float dtheta = angle ((x1p - cxp) / rx, (y1p - cyp) / ry, + (-x1p - cxp) / rx, (-y1p - cyp) / ry); + + if (!sweep && dtheta > 0.f) dtheta -= 2.f * (float) M_PI; + if (sweep && dtheta < 0.f) dtheta += 2.f * (float) M_PI; + + *cx_out = cx; *cy_out = cy; + *theta1_out = theta1; *dtheta_out = dtheta; + *rx_out = rx; *ry_out = ry; +} + +void +hb_raster_svg_parse_path_data (hb_svg_str_t d, hb_draw_funcs_t *dfuncs, void *draw_data) +{ + hb_draw_state_t st = HB_DRAW_STATE_DEFAULT; + hb_svg_float_parser_t fp (d); + + float cur_x = 0, cur_y = 0; + float start_x = 0, start_y = 0; + float last_cx = 0, last_cy = 0; + char last_cmd = 0; + char cmd = 0; + + while (fp.p < fp.end) + { + fp.skip_ws_comma (); + if (fp.p >= fp.end) break; + + char c = *fp.p; + if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) + { + cmd = c; + fp.p++; + } + + switch (cmd) + { + case 'M': case 'm': + { + float x = fp.next_float (); + float y = fp.next_float (); + if (cmd == 'm') { x += cur_x; y += cur_y; } + hb_draw_move_to (dfuncs, draw_data, &st, x, y); + cur_x = start_x = x; + cur_y = start_y = y; + cmd = (cmd == 'M') ? 'L' : 'l'; + last_cmd = 'M'; + continue; + } + case 'L': case 'l': + { + float x = fp.next_float (); + float y = fp.next_float (); + if (cmd == 'l') { x += cur_x; y += cur_y; } + hb_draw_line_to (dfuncs, draw_data, &st, x, y); + cur_x = x; cur_y = y; + break; + } + case 'H': case 'h': + { + float x = fp.next_float (); + if (cmd == 'h') x += cur_x; + hb_draw_line_to (dfuncs, draw_data, &st, x, cur_y); + cur_x = x; + break; + } + case 'V': case 'v': + { + float y = fp.next_float (); + if (cmd == 'v') y += cur_y; + hb_draw_line_to (dfuncs, draw_data, &st, cur_x, y); + cur_y = y; + break; + } + case 'C': case 'c': + { + float x1 = fp.next_float (); + float y1 = fp.next_float (); + float x2 = fp.next_float (); + float y2 = fp.next_float (); + float x = fp.next_float (); + float y = fp.next_float (); + if (cmd == 'c') + { x1 += cur_x; y1 += cur_y; x2 += cur_x; y2 += cur_y; x += cur_x; y += cur_y; } + hb_draw_cubic_to (dfuncs, draw_data, &st, x1, y1, x2, y2, x, y); + last_cx = x2; last_cy = y2; + cur_x = x; cur_y = y; + break; + } + case 'S': case 's': + { + float cx1, cy1; + if (last_cmd == 'C' || last_cmd == 'c' || last_cmd == 'S' || last_cmd == 's') + { cx1 = 2 * cur_x - last_cx; cy1 = 2 * cur_y - last_cy; } + else + { cx1 = cur_x; cy1 = cur_y; } + float x2 = fp.next_float (); + float y2 = fp.next_float (); + float x = fp.next_float (); + float y = fp.next_float (); + if (cmd == 's') + { x2 += cur_x; y2 += cur_y; x += cur_x; y += cur_y; } + hb_draw_cubic_to (dfuncs, draw_data, &st, cx1, cy1, x2, y2, x, y); + last_cx = x2; last_cy = y2; + cur_x = x; cur_y = y; + break; + } + case 'Q': case 'q': + { + float x1 = fp.next_float (); + float y1 = fp.next_float (); + float x = fp.next_float (); + float y = fp.next_float (); + if (cmd == 'q') + { x1 += cur_x; y1 += cur_y; x += cur_x; y += cur_y; } + hb_draw_quadratic_to (dfuncs, draw_data, &st, x1, y1, x, y); + last_cx = x1; last_cy = y1; + cur_x = x; cur_y = y; + break; + } + case 'T': case 't': + { + float cx1, cy1; + if (last_cmd == 'Q' || last_cmd == 'q' || last_cmd == 'T' || last_cmd == 't') + { cx1 = 2 * cur_x - last_cx; cy1 = 2 * cur_y - last_cy; } + else + { cx1 = cur_x; cy1 = cur_y; } + float x = fp.next_float (); + float y = fp.next_float (); + if (cmd == 't') { x += cur_x; y += cur_y; } + hb_draw_quadratic_to (dfuncs, draw_data, &st, cx1, cy1, x, y); + last_cx = cx1; last_cy = cy1; + cur_x = x; cur_y = y; + break; + } + case 'A': case 'a': + { + float rx = fp.next_float (); + float ry = fp.next_float (); + float x_rot = fp.next_float (); + bool large_arc = fp.next_flag (); + bool sweep = fp.next_flag (); + float x = fp.next_float (); + float y = fp.next_float (); + if (cmd == 'a') { x += cur_x; y += cur_y; } + + if (fabsf (x - cur_x) < 1e-6f && fabsf (y - cur_y) < 1e-6f) + { + cur_x = x; cur_y = y; + break; + } + + float cx, cy, theta1, dtheta, adj_rx, adj_ry; + svg_arc_endpoint_to_center (cur_x, cur_y, x, y, + rx, ry, x_rot, + large_arc, sweep, + &cx, &cy, &theta1, &dtheta, + &adj_rx, &adj_ry); + + float phi = x_rot * (float) M_PI / 180.f; + svg_arc_to_cubics (dfuncs, draw_data, &st, + cx, cy, adj_rx, adj_ry, phi, theta1, dtheta); + cur_x = x; cur_y = y; + break; + } + case 'Z': case 'z': + hb_draw_close_path (dfuncs, draw_data, &st); + cur_x = start_x; + cur_y = start_y; + break; + + default: + fp.p++; + continue; + } + + last_cmd = cmd; + } +} + +static void +svg_rect_to_path (float x, float y, float w, float h, float rx, float ry, + hb_draw_funcs_t *dfuncs, void *draw_data) +{ + hb_draw_state_t st = HB_DRAW_STATE_DEFAULT; + if (rx < 0.f || ry < 0.f) + return; + + if (rx <= 0 && ry <= 0) + { + hb_draw_move_to (dfuncs, draw_data, &st, x, y); + hb_draw_line_to (dfuncs, draw_data, &st, x + w, y); + hb_draw_line_to (dfuncs, draw_data, &st, x + w, y + h); + hb_draw_line_to (dfuncs, draw_data, &st, x, y + h); + hb_draw_close_path (dfuncs, draw_data, &st); + return; + } + + if (rx <= 0) rx = ry; + if (ry <= 0) ry = rx; + rx = hb_min (rx, w / 2); + ry = hb_min (ry, h / 2); + + float kx = rx * 0.5522847498f; + float ky = ry * 0.5522847498f; + + hb_draw_move_to (dfuncs, draw_data, &st, x + rx, y); + hb_draw_line_to (dfuncs, draw_data, &st, x + w - rx, y); + hb_draw_cubic_to (dfuncs, draw_data, &st, + x + w - rx + kx, y, + x + w, y + ry - ky, + x + w, y + ry); + hb_draw_line_to (dfuncs, draw_data, &st, x + w, y + h - ry); + hb_draw_cubic_to (dfuncs, draw_data, &st, + x + w, y + h - ry + ky, + x + w - rx + kx, y + h, + x + w - rx, y + h); + hb_draw_line_to (dfuncs, draw_data, &st, x + rx, y + h); + hb_draw_cubic_to (dfuncs, draw_data, &st, + x + rx - kx, y + h, + x, y + h - ry + ky, + x, y + h - ry); + hb_draw_line_to (dfuncs, draw_data, &st, x, y + ry); + hb_draw_cubic_to (dfuncs, draw_data, &st, + x, y + ry - ky, + x + rx - kx, y, + x + rx, y); + hb_draw_close_path (dfuncs, draw_data, &st); +} + +static void +svg_circle_to_path (float cx, float cy, float r, + hb_draw_funcs_t *dfuncs, void *draw_data) +{ + hb_draw_state_t st = HB_DRAW_STATE_DEFAULT; + float k = r * 0.5522847498f; + + hb_draw_move_to (dfuncs, draw_data, &st, cx + r, cy); + hb_draw_cubic_to (dfuncs, draw_data, &st, + cx + r, cy + k, + cx + k, cy + r, + cx, cy + r); + hb_draw_cubic_to (dfuncs, draw_data, &st, + cx - k, cy + r, + cx - r, cy + k, + cx - r, cy); + hb_draw_cubic_to (dfuncs, draw_data, &st, + cx - r, cy - k, + cx - k, cy - r, + cx, cy - r); + hb_draw_cubic_to (dfuncs, draw_data, &st, + cx + k, cy - r, + cx + r, cy - k, + cx + r, cy); + hb_draw_close_path (dfuncs, draw_data, &st); +} + +static void +svg_ellipse_to_path (float cx, float cy, float rx, float ry, + hb_draw_funcs_t *dfuncs, void *draw_data) +{ + hb_draw_state_t st = HB_DRAW_STATE_DEFAULT; + float kx = rx * 0.5522847498f; + float ky = ry * 0.5522847498f; + + hb_draw_move_to (dfuncs, draw_data, &st, cx + rx, cy); + hb_draw_cubic_to (dfuncs, draw_data, &st, + cx + rx, cy + ky, + cx + kx, cy + ry, + cx, cy + ry); + hb_draw_cubic_to (dfuncs, draw_data, &st, + cx - kx, cy + ry, + cx - rx, cy + ky, + cx - rx, cy); + hb_draw_cubic_to (dfuncs, draw_data, &st, + cx - rx, cy - ky, + cx - kx, cy - ry, + cx, cy - ry); + hb_draw_cubic_to (dfuncs, draw_data, &st, + cx + kx, cy - ry, + cx + rx, cy - ky, + cx + rx, cy); + hb_draw_close_path (dfuncs, draw_data, &st); +} + +static void +svg_line_to_path (float x1, float y1, float x2, float y2, + hb_draw_funcs_t *dfuncs, void *draw_data) +{ + hb_draw_state_t st = HB_DRAW_STATE_DEFAULT; + hb_draw_move_to (dfuncs, draw_data, &st, x1, y1); + hb_draw_line_to (dfuncs, draw_data, &st, x2, y2); +} + +static void +svg_polygon_to_path (hb_svg_str_t points, bool close, + hb_draw_funcs_t *dfuncs, void *draw_data) +{ + hb_draw_state_t st = HB_DRAW_STATE_DEFAULT; + hb_svg_float_parser_t fp (points); + bool first = true; + while (fp.has_more ()) + { + float x = fp.next_float (); + float y = fp.next_float (); + if (first) + { + hb_draw_move_to (dfuncs, draw_data, &st, x, y); + first = false; + } + else + hb_draw_line_to (dfuncs, draw_data, &st, x, y); + } + if (close && !first) + hb_draw_close_path (dfuncs, draw_data, &st); +} + +void +hb_raster_svg_shape_path_emit (hb_draw_funcs_t *dfuncs, void *draw_data, void *user_data) +{ + hb_svg_shape_emit_data_t *shape = (hb_svg_shape_emit_data_t *) user_data; + switch (shape->type) + { + case hb_svg_shape_emit_data_t::SHAPE_PATH: + hb_raster_svg_parse_path_data (shape->str_data, dfuncs, draw_data); + break; + case hb_svg_shape_emit_data_t::SHAPE_RECT: + svg_rect_to_path (shape->params[0], shape->params[1], + shape->params[2], shape->params[3], + shape->params[4], shape->params[5], + dfuncs, draw_data); + break; + case hb_svg_shape_emit_data_t::SHAPE_CIRCLE: + svg_circle_to_path (shape->params[0], shape->params[1], shape->params[2], + dfuncs, draw_data); + break; + case hb_svg_shape_emit_data_t::SHAPE_ELLIPSE: + svg_ellipse_to_path (shape->params[0], shape->params[1], + shape->params[2], shape->params[3], + dfuncs, draw_data); + break; + case hb_svg_shape_emit_data_t::SHAPE_LINE: + svg_line_to_path (shape->params[0], shape->params[1], + shape->params[2], shape->params[3], + dfuncs, draw_data); + break; + case hb_svg_shape_emit_data_t::SHAPE_POLYLINE: + svg_polygon_to_path (shape->str_data, false, dfuncs, draw_data); + break; + case hb_svg_shape_emit_data_t::SHAPE_POLYGON: + svg_polygon_to_path (shape->str_data, true, dfuncs, draw_data); + break; + } +} + +bool +hb_raster_svg_parse_shape_tag (hb_svg_xml_parser_t &parser, + hb_svg_shape_emit_data_t *shape) +{ + hb_svg_attr_view_t attrs (parser); + hb_svg_style_props_t style_props; + svg_parse_style_props (attrs.get ("style"), &style_props); + hb_svg_str_t tag = parser.tag_name; + if (tag.eq ("path")) + { + hb_svg_str_t d = svg_pick_attr_or_style (parser, style_props.d, "d"); + if (!d.len) return false; + shape->type = hb_svg_shape_emit_data_t::SHAPE_PATH; + shape->str_data = d; + return true; + } + if (tag.eq ("rect")) + { + float w = svg_parse_float (svg_pick_attr_or_style (parser, style_props.width, "width")); + float h = svg_parse_float (svg_pick_attr_or_style (parser, style_props.height, "height")); + if (w <= 0 || h <= 0) return false; + float rx = svg_parse_float (svg_pick_attr_or_style (parser, style_props.rx, "rx")); + float ry = svg_parse_float (svg_pick_attr_or_style (parser, style_props.ry, "ry")); + if (rx < 0.f || ry < 0.f) return false; + shape->type = hb_svg_shape_emit_data_t::SHAPE_RECT; + shape->params[0] = svg_parse_float (svg_pick_attr_or_style (parser, style_props.x, "x")); + shape->params[1] = svg_parse_float (svg_pick_attr_or_style (parser, style_props.y, "y")); + shape->params[2] = w; + shape->params[3] = h; + shape->params[4] = rx; + shape->params[5] = ry; + return true; + } + if (tag.eq ("circle")) + { + float r = svg_parse_float (svg_pick_attr_or_style (parser, style_props.r, "r")); + if (r <= 0) return false; + shape->type = hb_svg_shape_emit_data_t::SHAPE_CIRCLE; + shape->params[0] = svg_parse_float (svg_pick_attr_or_style (parser, style_props.cx, "cx")); + shape->params[1] = svg_parse_float (svg_pick_attr_or_style (parser, style_props.cy, "cy")); + shape->params[2] = r; + return true; + } + if (tag.eq ("ellipse")) + { + float rx = svg_parse_float (svg_pick_attr_or_style (parser, style_props.rx, "rx")); + float ry = svg_parse_float (svg_pick_attr_or_style (parser, style_props.ry, "ry")); + if (rx <= 0 || ry <= 0) return false; + shape->type = hb_svg_shape_emit_data_t::SHAPE_ELLIPSE; + shape->params[0] = svg_parse_float (svg_pick_attr_or_style (parser, style_props.cx, "cx")); + shape->params[1] = svg_parse_float (svg_pick_attr_or_style (parser, style_props.cy, "cy")); + shape->params[2] = rx; + shape->params[3] = ry; + return true; + } + if (tag.eq ("line")) + { + shape->type = hb_svg_shape_emit_data_t::SHAPE_LINE; + shape->params[0] = svg_parse_float (svg_pick_attr_or_style (parser, style_props.x1, "x1")); + shape->params[1] = svg_parse_float (svg_pick_attr_or_style (parser, style_props.y1, "y1")); + shape->params[2] = svg_parse_float (svg_pick_attr_or_style (parser, style_props.x2, "x2")); + shape->params[3] = svg_parse_float (svg_pick_attr_or_style (parser, style_props.y2, "y2")); + return true; + } + if (tag.eq ("polyline")) + { + hb_svg_str_t points = svg_pick_attr_or_style (parser, style_props.points, "points"); + if (!points.len) return false; + shape->type = hb_svg_shape_emit_data_t::SHAPE_POLYLINE; + shape->str_data = points; + return true; + } + if (tag.eq ("polygon")) + { + hb_svg_str_t points = svg_pick_attr_or_style (parser, style_props.points, "points"); + if (!points.len) return false; + shape->type = hb_svg_shape_emit_data_t::SHAPE_POLYGON; + shape->str_data = points; + return true; + } + return false; +} diff --git a/src/hb-raster-svg-parse.hh b/src/hb-raster-svg-parse.hh new file mode 100644 index 000000000..ac4bab27b --- /dev/null +++ b/src/hb-raster-svg-parse.hh @@ -0,0 +1,355 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#ifndef HB_RASTER_SVG_PARSE_HH +#define HB_RASTER_SVG_PARSE_HH + +#include "hb.hh" + +#include "hb-raster-svg-base.hh" +#include "hb-draw.h" + +#include +#include + +enum hb_svg_token_type_t +{ + SVG_TOKEN_OPEN_TAG, + SVG_TOKEN_CLOSE_TAG, + SVG_TOKEN_SELF_CLOSE_TAG, + SVG_TOKEN_TEXT, + SVG_TOKEN_EOF +}; + +struct hb_svg_attr_t +{ + hb_svg_str_t name; + hb_svg_str_t value; +}; + +struct hb_svg_xml_parser_t +{ + enum { SVG_MAX_ATTRS_PER_TAG = 256 }; + + const char *p; + const char *end; + const char *tag_start = nullptr; + + hb_svg_str_t tag_name; + hb_vector_t attrs; + bool self_closing; + + hb_svg_xml_parser_t (const char *data, unsigned len) + : p (data), end (data + len) {} + + void skip_ws () + { + while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) + p++; + } + + hb_svg_str_t read_name () + { + const char *start = p; + while (p < end && *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r' && + *p != '>' && *p != '/' && *p != '=') + p++; + return {start, (unsigned) (p - start)}; + } + + hb_svg_str_t read_attr_value () + { + if (p >= end) return {}; + char quote = *p; + if (quote != '"' && quote != '\'') return {}; + p++; + const char *start = p; + while (p < end && *p != quote) + p++; + hb_svg_str_t val = {start, (unsigned) (p - start)}; + if (p < end) p++; /* skip closing quote */ + return val; + } + + void parse_attrs () + { + attrs.clear (); + while (p < end) + { + skip_ws (); + if (p >= end || *p == '>' || *p == '/') break; + hb_svg_str_t name = read_name (); + if (!name.len) { p++; continue; } + skip_ws (); + if (p < end && *p == '=') + { + p++; + skip_ws (); + hb_svg_str_t val = read_attr_value (); + if (attrs.length < SVG_MAX_ATTRS_PER_TAG) + { + hb_svg_attr_t attr = {name, val}; + attrs.push (attr); + } + } + else + { + if (attrs.length < SVG_MAX_ATTRS_PER_TAG) + { + hb_svg_attr_t attr = {name, {}}; + attrs.push (attr); + } + } + } + } + + hb_svg_token_type_t next () + { + while (p < end) + { + if (*p != '<') + { + while (p < end && *p != '<') p++; + continue; + } + + tag_start = p; + p++; /* skip '<' */ + if (p >= end) return SVG_TOKEN_EOF; + + if (*p == '!') + { + if (p + 2 < end && p[1] == '-' && p[2] == '-') + { + p += 3; + while (p + 2 < end && !(p[0] == '-' && p[1] == '-' && p[2] == '>')) + p++; + if (p + 2 < end) p += 3; + } + else + { + while (p < end && *p != '>') p++; + if (p < end) p++; + } + continue; + } + if (*p == '?') + { + while (p + 1 < end && !(p[0] == '?' && p[1] == '>')) + p++; + if (p + 1 < end) p += 2; + continue; + } + + if (*p == '/') + { + p++; + tag_name = read_name (); + while (p < end && *p != '>') p++; + if (p < end) p++; + attrs.clear (); + self_closing = false; + return SVG_TOKEN_CLOSE_TAG; + } + + tag_name = read_name (); + parse_attrs (); + + self_closing = false; + skip_ws (); + if (p < end && *p == '/') + { + self_closing = true; + p++; + } + if (p < end && *p == '>') + p++; + + return self_closing ? SVG_TOKEN_SELF_CLOSE_TAG : SVG_TOKEN_OPEN_TAG; + } + return SVG_TOKEN_EOF; + } + + hb_svg_str_t find_attr (const char *name) const + { + for (unsigned i = 0; i < attrs.length; i++) + if (attrs[i].name.eq (name)) + return attrs[i].value; + return {}; + } +}; + +static inline hb_svg_str_t +svg_pick_attr_or_style (const hb_svg_xml_parser_t &parser, + hb_svg_str_t style_value, + const char *attr_name) +{ + return style_value.is_null () ? parser.find_attr (attr_name) : style_value; +} + +struct hb_svg_attr_view_t +{ + const hb_svg_xml_parser_t &parser; + enum { CACHE_SIZE = 16 }; + struct entry_t + { + const char *name = nullptr; + hb_svg_str_t value; + }; + entry_t cache[CACHE_SIZE]; + unsigned cache_len = 0; + + hb_svg_attr_view_t (const hb_svg_xml_parser_t &p) : parser (p) {} + + hb_svg_str_t get (const char *name) + { + for (unsigned i = 0; i < cache_len; i++) + if (strcmp (cache[i].name, name) == 0) + return cache[i].value; + + hb_svg_str_t value = parser.find_attr (name); + if (cache_len < CACHE_SIZE) + { + cache[cache_len].name = name; + cache[cache_len].value = value; + cache_len++; + } + return value; + } +}; + +struct hb_svg_transform_t +{ + float xx = 1, yx = 0, xy = 0, yy = 1, dx = 0, dy = 0; + + void multiply (const hb_svg_transform_t &other) + { + float nxx = xx * other.xx + xy * other.yx; + float nyx = yx * other.xx + yy * other.yx; + float nxy = xx * other.xy + xy * other.yy; + float nyy = yx * other.xy + yy * other.yy; + float ndx = xx * other.dx + xy * other.dy + dx; + float ndy = yx * other.dx + yy * other.dy + dy; + xx = nxx; yx = nyx; xy = nxy; yy = nyy; dx = ndx; dy = ndy; + } +}; + +struct hb_svg_float_parser_t +{ + const char *p; + const char *end; + + hb_svg_float_parser_t (hb_svg_str_t s) : p (s.data), end (s.data + s.len) {} + + void skip_ws_comma () + { + while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || *p == ',')) + p++; + } + + bool has_more () const { return p < end; } + + float next_float () + { + skip_ws_comma (); + if (p >= end) return 0.f; + const char *start = p; + char buf[64]; + unsigned n = 0; + bool has_digit = false; + if (p < end && (*p == '-' || *p == '+')) + buf[n++] = *p++; + while (p < end && n < sizeof (buf) - 1 && *p >= '0' && *p <= '9') + { + buf[n++] = *p++; + has_digit = true; + } + if (p < end && n < sizeof (buf) - 1 && *p == '.') + { + buf[n++] = *p++; + while (p < end && n < sizeof (buf) - 1 && *p >= '0' && *p <= '9') + { + buf[n++] = *p++; + has_digit = true; + } + } + if (p < end && n < sizeof (buf) - 1 && (*p == 'e' || *p == 'E')) + { + buf[n++] = *p++; + if (p < end && n < sizeof (buf) - 1 && (*p == '+' || *p == '-')) + buf[n++] = *p++; + bool has_exp_digit = false; + while (p < end && n < sizeof (buf) - 1 && *p >= '0' && *p <= '9') + { + buf[n++] = *p++; + has_exp_digit = true; + } + if (!has_exp_digit) + { + p = start; + has_digit = false; + } + } + if (!has_digit) + { + if (p < end) p++; + return 0.f; + } + buf[n] = '\0'; + float v = strtof (buf, nullptr); + return isfinite (v) ? v : 0.f; + } + + bool next_flag () + { + skip_ws_comma (); + if (p >= end) return false; + bool v = *p != '0'; + p++; + return v; + } +}; + +static inline float +svg_parse_float (hb_svg_str_t s) +{ + return s.to_float (); +} + +struct hb_svg_shape_emit_data_t +{ + enum { SHAPE_PATH, SHAPE_RECT, SHAPE_CIRCLE, SHAPE_ELLIPSE, + SHAPE_LINE, SHAPE_POLYLINE, SHAPE_POLYGON } type; + hb_svg_str_t str_data; + float params[6]; +}; + +HB_INTERNAL bool hb_raster_svg_parse_transform (hb_svg_str_t s, hb_svg_transform_t *out); +HB_INTERNAL void hb_raster_svg_parse_path_data (hb_svg_str_t d, hb_draw_funcs_t *dfuncs, void *draw_data); +HB_INTERNAL void hb_raster_svg_shape_path_emit (hb_draw_funcs_t *dfuncs, void *draw_data, void *user_data); +HB_INTERNAL bool hb_raster_svg_parse_shape_tag (hb_svg_xml_parser_t &parser, hb_svg_shape_emit_data_t *shape); + +#endif /* HB_RASTER_SVG_PARSE_HH */ diff --git a/src/hb-raster-svg-render.cc b/src/hb-raster-svg-render.cc new file mode 100644 index 000000000..aa0dd4bdf --- /dev/null +++ b/src/hb-raster-svg-render.cc @@ -0,0 +1,530 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#include "hb.hh" + +#include "hb-face.hh" +#include "hb-raster-svg.hh" +#include "hb-raster-svg-base.hh" +#include "hb-raster-svg-parse.hh" +#include "hb-raster-svg-context.hh" +#include "hb-raster-svg-defs-scan.hh" +#include "hb-raster-svg-gradient.hh" +#include "hb-raster-svg-clip.hh" +#include "hb-raster-svg-bbox.hh" +#include "hb-raster-svg-fill.hh" +#include "hb-raster-svg-use.hh" + +#include +#include + + +#define SVG_MAX_DEPTH 32 + +/* + * 11. Element renderer — recursive SVG rendering + */ + +static void svg_render_element (hb_svg_render_context_t *ctx, + hb_svg_xml_parser_t &parser, + const struct hb_svg_cascade_t &inherited); + +/* Gradient def parsing lives in hb-raster-svg-gradient.* */ + +/* Clip-path defs and push helpers live in hb-raster-svg-clip.* */ + +/* Render a single shape element */ +static void +svg_render_shape (hb_svg_render_context_t *ctx, + hb_svg_shape_emit_data_t &shape, + const hb_svg_cascade_t &state, + hb_svg_str_t transform_str) +{ + bool has_transform = transform_str.len > 0; + bool has_opacity = state.opacity < 1.f; + bool has_clip_path = false; + + if (has_opacity) + ctx->push_group (); + + if (has_transform) + { + hb_svg_transform_t t; + hb_raster_svg_parse_transform (transform_str, &t); + ctx->push_transform (t.xx, t.yx, t.xy, t.yy, t.dx, t.dy); + } + + hb_extents_t<> bbox; + bool has_bbox = hb_raster_svg_compute_shape_bbox (shape, &bbox); + has_clip_path = hb_raster_svg_push_clip_path_ref (ctx->paint, &ctx->defs, state.clip_path, + has_bbox ? &bbox : nullptr); + + /* Clip with shape path, then fill */ + hb_raster_paint_push_clip_path (ctx->paint, hb_raster_svg_shape_path_emit, &shape); + + /* Default fill is black */ + if (state.fill.is_null ()) + { + hb_color_t black = HB_COLOR (0, 0, 0, 255); + if (state.fill_opacity < 1.f) + black = HB_COLOR (0, 0, 0, (uint8_t) (255 * state.fill_opacity + 0.5f)); + ctx->paint_color (black); + } + else + { + hb_svg_fill_context_t fill_ctx = {ctx->paint, ctx->pfuncs, ctx->font, ctx->palette, &ctx->defs}; + hb_raster_svg_emit_fill (&fill_ctx, state.fill, state.fill_opacity, has_bbox ? &bbox : nullptr, state.color); + } + + ctx->pop_clip (); + if (has_clip_path) + ctx->pop_clip (); + + if (has_transform) + ctx->pop_transform (); + + if (has_opacity) + ctx->pop_group (HB_PAINT_COMPOSITE_MODE_SRC_OVER); +} + +static void +svg_render_container_element (hb_svg_render_context_t *ctx, + hb_svg_xml_parser_t &parser, + hb_svg_str_t tag, + bool self_closing, + const hb_svg_cascade_t &state, + hb_svg_str_t transform_str, + hb_svg_str_t clip_path_str) +{ + bool has_transform = transform_str.len > 0; + bool has_opacity = state.opacity < 1.f; + bool has_clip = false; + bool has_viewbox = false; + bool has_viewbox_transform = false; + bool has_svg_translate = false; + float svg_x = 0.f, svg_y = 0.f; + float viewport_w = 0.f, viewport_h = 0.f; + hb_svg_transform_t viewbox_t; + float vb_x = 0, vb_y = 0, vb_w = 0, vb_h = 0; + + if (tag.eq ("svg") || tag.eq ("symbol")) + { + hb_svg_style_props_t geom_style_props; + svg_parse_style_props (parser.find_attr ("style"), &geom_style_props); + + if (tag.eq ("svg")) + { + svg_x = hb_raster_svg_parse_non_percent_length (svg_pick_attr_or_style (parser, geom_style_props.x, "x")); + svg_y = hb_raster_svg_parse_non_percent_length (svg_pick_attr_or_style (parser, geom_style_props.y, "y")); + has_svg_translate = (svg_x != 0.f || svg_y != 0.f); + } + + hb_svg_str_t viewbox_str = parser.find_attr ("viewBox"); + if (hb_raster_svg_parse_viewbox (viewbox_str, &vb_x, &vb_y, &vb_w, &vb_h)) + { + has_viewbox = true; + + if (tag.eq ("svg")) + { + viewport_w = hb_raster_svg_parse_non_percent_length (svg_pick_attr_or_style (parser, geom_style_props.width, "width")); + viewport_h = hb_raster_svg_parse_non_percent_length (svg_pick_attr_or_style (parser, geom_style_props.height, "height")); + if (!(viewport_w > 0.f && viewport_h > 0.f)) + { + viewport_w = vb_w; + viewport_h = vb_h; + } + has_viewbox_transform = + hb_raster_svg_compute_viewbox_transform (viewport_w, viewport_h, + vb_x, vb_y, vb_w, vb_h, + parser.find_attr ("preserveAspectRatio"), + &viewbox_t); + } + } + } + + if (ctx->suppress_viewbox_once) + { + has_viewbox = false; + has_viewbox_transform = false; + ctx->suppress_viewbox_once = false; + } + + if (has_opacity) + ctx->push_group (); + + if (has_transform) + { + hb_svg_transform_t t; + hb_raster_svg_parse_transform (transform_str, &t); + ctx->push_transform (t.xx, t.yx, t.xy, t.yy, t.dx, t.dy); + } + + if (has_svg_translate) + ctx->push_transform (1, 0, 0, 1, svg_x, svg_y); + + if (has_viewbox_transform) + ctx->push_transform (viewbox_t.xx, viewbox_t.yx, viewbox_t.xy, viewbox_t.yy, + viewbox_t.dx, viewbox_t.dy); + else if (has_viewbox && vb_w > 0 && vb_h > 0) + ctx->push_transform (1, 0, 0, 1, -vb_x, -vb_y); + + has_clip = hb_raster_svg_push_clip_path_ref (ctx->paint, &ctx->defs, clip_path_str, nullptr); + + if (!self_closing) + { + int depth = 1; + while (depth > 0) + { + hb_svg_token_type_t tok = parser.next (); + if (tok == SVG_TOKEN_EOF) break; + + if (tok == SVG_TOKEN_CLOSE_TAG) + { + depth--; + continue; + } + + if (tok == SVG_TOKEN_OPEN_TAG || tok == SVG_TOKEN_SELF_CLOSE_TAG) + { + hb_svg_str_t child_tag = parser.tag_name; + if (parser.tag_name.eq ("defs")) + { + if (tok != SVG_TOKEN_SELF_CLOSE_TAG) + { + hb_svg_defs_scan_context_t scan_ctx = { + &ctx->defs, ctx->pfuncs, ctx->paint, + ctx->foreground, hb_font_get_face (ctx->font), + ctx->palette, + ctx->doc_start, ctx->doc_len, + ctx->svg_accel, ctx->doc_cache + }; + hb_raster_svg_process_defs_element (&scan_ctx, parser); + } + continue; + } + svg_render_element (ctx, parser, state); + if (tok == SVG_TOKEN_OPEN_TAG && + !hb_raster_svg_tag_is_container_or_use (child_tag)) + { + /* Skip children of non-container elements we don't handle. */ + int skip_depth = 1; + while (skip_depth > 0) + { + hb_svg_token_type_t st = parser.next (); + if (st == SVG_TOKEN_EOF) break; + if (st == SVG_TOKEN_CLOSE_TAG) skip_depth--; + else if (st == SVG_TOKEN_OPEN_TAG) skip_depth++; + } + } + } + } + } + + if (has_viewbox_transform || (has_viewbox && vb_w > 0 && vb_h > 0)) + ctx->pop_transform (); + + if (has_svg_translate) + ctx->pop_transform (); + + if (has_clip) + ctx->pop_clip (); + + if (has_transform) + ctx->pop_transform (); + + if (has_opacity) + ctx->pop_group (HB_PAINT_COMPOSITE_MODE_SRC_OVER); +} + +static bool +svg_render_primitive_shape_element (hb_svg_render_context_t *ctx, + hb_svg_xml_parser_t &parser, + const hb_svg_cascade_t &state, + hb_svg_str_t transform_str) +{ + hb_svg_str_t tag = parser.tag_name; + if (!(tag.eq ("path") || tag.eq ("rect") || tag.eq ("circle") || + tag.eq ("ellipse") || tag.eq ("line") || tag.eq ("polyline") || + tag.eq ("polygon"))) + return false; + + hb_svg_shape_emit_data_t shape; + if (hb_raster_svg_parse_shape_tag (parser, &shape)) + svg_render_shape (ctx, shape, state, transform_str); + return true; +} + +static void +svg_render_use_callback (void *render_user, + hb_svg_xml_parser_t &parser, + const void *state, + bool viewport_mapped) +{ + hb_svg_render_context_t *ctx = (hb_svg_render_context_t *) render_user; + bool old_suppress = ctx->suppress_viewbox_once; + bool old_allow_symbol = ctx->allow_symbol_render_once; + if (viewport_mapped) + ctx->suppress_viewbox_once = true; + if (parser.tag_name.eq ("symbol")) + ctx->allow_symbol_render_once = true; + svg_render_element (ctx, parser, *(const hb_svg_cascade_t *) state); + ctx->suppress_viewbox_once = old_suppress; + ctx->allow_symbol_render_once = old_allow_symbol; +} + +static void +svg_skip_subtree (hb_svg_xml_parser_t &parser) +{ + int depth = 1; + while (depth > 0) + { + hb_svg_token_type_t tok = parser.next (); + if (tok == SVG_TOKEN_EOF) break; + if (tok == SVG_TOKEN_CLOSE_TAG) depth--; + else if (tok == SVG_TOKEN_OPEN_TAG) depth++; + } +} + +/* Render one element (may be a container or shape) */ +static void +svg_render_element (hb_svg_render_context_t *ctx, + hb_svg_xml_parser_t &parser, + const hb_svg_cascade_t &inherited) +{ + if (ctx->depth >= SVG_MAX_DEPTH) return; + + const HB_UNUSED unsigned transform_depth = ctx->paint->transform_stack.length; + const HB_UNUSED unsigned clip_depth = ctx->paint->clip_stack.length; + const HB_UNUSED unsigned surface_depth = ctx->paint->surface_stack.length; + + ctx->depth++; + + hb_svg_str_t tag = parser.tag_name; + bool self_closing = parser.self_closing; + + /* Extract common attributes */ + hb_svg_str_t style = parser.find_attr ("style"); + hb_svg_style_props_t style_props; + svg_parse_style_props (style, &style_props); + hb_svg_str_t fill_attr = svg_pick_attr_or_style (parser, style_props.fill, "fill"); + hb_svg_str_t fill_opacity_str = svg_pick_attr_or_style (parser, style_props.fill_opacity, "fill-opacity"); + hb_svg_str_t opacity_str = svg_pick_attr_or_style (parser, style_props.opacity, "opacity"); + hb_svg_str_t transform_str = svg_pick_attr_or_style (parser, style_props.transform, "transform"); + hb_svg_str_t clip_path_attr = svg_pick_attr_or_style (parser, style_props.clip_path, "clip-path"); + hb_svg_str_t display_str = svg_pick_attr_or_style (parser, style_props.display, "display"); + hb_svg_str_t color_str = svg_pick_attr_or_style (parser, style_props.color, "color"); + hb_svg_str_t visibility_str = svg_pick_attr_or_style (parser, style_props.visibility, "visibility"); + + hb_svg_cascade_t state = inherited; + state.fill = (fill_attr.is_null () || svg_str_is_inherit (fill_attr)) ? inherited.fill : fill_attr; + state.fill_opacity = (fill_opacity_str.len && !svg_str_is_inherit (fill_opacity_str)) + ? svg_parse_float_clamped01 (fill_opacity_str) + : inherited.fill_opacity; + state.opacity = (opacity_str.len && !svg_str_is_inherit (opacity_str) && !svg_str_is_none (opacity_str)) + ? svg_parse_float_clamped01 (opacity_str) + : (svg_str_is_inherit (opacity_str) ? inherited.opacity : 1.f); + state.clip_path = (clip_path_attr.is_null () || svg_str_is_inherit (clip_path_attr)) + ? inherited.clip_path + : clip_path_attr; + if (svg_str_is_inherit (transform_str) || svg_str_is_none (transform_str)) + transform_str = {}; + state.color = inherited.color; + bool is_none = false; + if (color_str.len && !color_str.trim ().eq_ascii_ci ("inherit")) + state.color = hb_raster_svg_parse_color (color_str, ctx->pfuncs, ctx->paint, + inherited.color, hb_font_get_face (ctx->font), + ctx->palette, &is_none); + state.visibility = inherited.visibility; + hb_svg_str_t visibility_trim = visibility_str.trim (); + if (visibility_trim.len && !visibility_trim.eq_ascii_ci ("inherit")) + state.visibility = !(visibility_trim.eq_ascii_ci ("hidden") || + visibility_trim.eq_ascii_ci ("collapse")); + + if (display_str.trim ().eq_ascii_ci ("none")) + { + if (!self_closing) + svg_skip_subtree (parser); + ctx->depth--; + assert (ctx->paint->transform_stack.length == transform_depth); + assert (ctx->paint->clip_stack.length == clip_depth); + assert (ctx->paint->surface_stack.length == surface_depth); + return; + } + if (!state.visibility) + { + if (!self_closing) + svg_skip_subtree (parser); + ctx->depth--; + assert (ctx->paint->transform_stack.length == transform_depth); + assert (ctx->paint->clip_stack.length == clip_depth); + assert (ctx->paint->surface_stack.length == surface_depth); + return; + } + + if (tag.eq ("symbol") && !ctx->allow_symbol_render_once) + { + if (!self_closing) + svg_skip_subtree (parser); + ctx->depth--; + assert (ctx->paint->transform_stack.length == transform_depth); + assert (ctx->paint->clip_stack.length == clip_depth); + assert (ctx->paint->surface_stack.length == surface_depth); + return; + } + if (tag.eq ("symbol")) + ctx->allow_symbol_render_once = false; + + if (hb_raster_svg_tag_is_container (tag)) + svg_render_container_element (ctx, parser, tag, self_closing, + state, transform_str, state.clip_path); + else if (svg_render_primitive_shape_element (ctx, parser, state, transform_str)) + ; + else if (tag.eq ("use")) + { + hb_svg_use_context_t use_ctx = {ctx->paint, ctx->pfuncs, + ctx->doc_start, ctx->doc_len, + ctx->svg_accel, ctx->doc_cache, + &ctx->use_decycler}; + hb_raster_svg_render_use_element (&use_ctx, parser, &state, transform_str, + svg_render_use_callback, ctx); + } + + ctx->depth--; + + assert (ctx->paint->transform_stack.length == transform_depth); + assert (ctx->paint->clip_stack.length == clip_depth); + assert (ctx->paint->surface_stack.length == surface_depth); +} + + +/* + * 12. Entry point + */ + +hb_bool_t +hb_raster_svg_render (hb_raster_paint_t *paint, + hb_blob_t *blob, + hb_codepoint_t glyph, + hb_font_t *font, + unsigned palette, + hb_color_t foreground) +{ + unsigned data_len; + const char *data = hb_blob_get_data (blob, &data_len); + if (!data || !data_len) return false; + + hb_face_t *face = hb_font_get_face (font); + const OT::SVG::svg_doc_cache_t *doc_cache = nullptr; + unsigned doc_index = 0; + hb_codepoint_t start_glyph = HB_CODEPOINT_INVALID; + hb_codepoint_t end_glyph = HB_CODEPOINT_INVALID; + + if (face && + hb_ot_color_glyph_get_svg_document_index (face, glyph, &doc_index) && + hb_ot_color_get_svg_document_glyph_range (face, doc_index, &start_glyph, &end_glyph)) + doc_cache = face->table.SVG->get_or_create_doc_cache (blob, data, data_len, + doc_index, start_glyph, end_glyph); + + if (doc_cache) + data = face->table.SVG->doc_cache_get_svg (doc_cache, &data_len); + + hb_paint_funcs_t *pfuncs = hb_raster_paint_get_funcs (); + + hb_svg_render_context_t ctx; + ctx.paint = paint; + ctx.pfuncs = pfuncs; + ctx.font = font; + ctx.palette = palette; + ctx.foreground = foreground; + ctx.doc_start = data; + ctx.doc_len = data_len; + ctx.svg_accel = face ? face->table.SVG.get () : nullptr; + ctx.doc_cache = doc_cache; + + hb_svg_cascade_t initial_state; + initial_state.color = foreground; + + hb_svg_defs_scan_context_t scan_ctx = { + &ctx.defs, ctx.pfuncs, ctx.paint, + ctx.foreground, hb_font_get_face (ctx.font), + ctx.palette, + ctx.doc_start, ctx.doc_len, + ctx.svg_accel, ctx.doc_cache + }; + hb_raster_svg_collect_defs (&scan_ctx, data, data_len); + + bool found_glyph = false; + unsigned glyph_start = 0, glyph_end = 0; + if (doc_cache && face->table.SVG->doc_cache_get_glyph_span (doc_cache, glyph, &glyph_start, &glyph_end)) + { + hb_svg_xml_parser_t parser (data + glyph_start, glyph_end - glyph_start); + hb_svg_token_type_t tok = parser.next (); + if (tok == SVG_TOKEN_OPEN_TAG || tok == SVG_TOKEN_SELF_CLOSE_TAG) + { + hb_paint_push_font_transform (ctx.pfuncs, ctx.paint, font); + ctx.push_transform (1, 0, 0, -1, 0, 0); + svg_render_element (&ctx, parser, initial_state); + ctx.pop_transform (); + hb_paint_pop_transform (ctx.pfuncs, ctx.paint); + found_glyph = true; + } + } + else + { + /* Fallback for malformed/uncached docs: linear scan by glyph id. */ + char glyph_id_str[32]; + int glyph_id_len = snprintf (glyph_id_str, sizeof (glyph_id_str), "glyph%u", glyph); + if (glyph_id_len <= 0 || (unsigned) glyph_id_len >= sizeof (glyph_id_str)) + return false; + hb_svg_xml_parser_t parser (data, data_len); + while (true) + { + hb_svg_token_type_t tok = parser.next (); + if (tok == SVG_TOKEN_EOF) break; + + if (tok == SVG_TOKEN_OPEN_TAG || tok == SVG_TOKEN_SELF_CLOSE_TAG) + { + hb_svg_str_t id = parser.find_attr ("id"); + if (id.len) + { + if (id.len == (unsigned) glyph_id_len && + 0 == memcmp (id.data, glyph_id_str, (unsigned) glyph_id_len)) + { + hb_paint_push_font_transform (ctx.pfuncs, ctx.paint, font); + ctx.push_transform (1, 0, 0, -1, 0, 0); + svg_render_element (&ctx, parser, initial_state); + ctx.pop_transform (); + hb_paint_pop_transform (ctx.pfuncs, ctx.paint); + found_glyph = true; + break; + } + } + } + } + } + + return found_glyph; +} diff --git a/src/hb-raster-svg-use.cc b/src/hb-raster-svg-use.cc new file mode 100644 index 000000000..b4aa5ab47 --- /dev/null +++ b/src/hb-raster-svg-use.cc @@ -0,0 +1,100 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#include "hb.hh" + +#include "hb-raster-svg-use.hh" + +#include "hb-raster-svg-base.hh" + +void +hb_raster_svg_render_use_element (const hb_svg_use_context_t *ctx, + hb_svg_xml_parser_t &parser, + const void *state, + hb_svg_str_t transform_str, + hb_svg_use_render_cb_t render_cb, + void *render_user) +{ + hb_svg_str_t href = hb_raster_svg_find_href_attr (parser); + + hb_svg_str_t ref_id; + if (!hb_raster_svg_parse_local_id_ref (href, &ref_id, nullptr)) + return; + + float use_x = 0.f, use_y = 0.f, use_w = 0.f, use_h = 0.f; + hb_raster_svg_parse_use_geometry (parser, &use_x, &use_y, &use_w, &use_h); + + bool has_translate = (use_x != 0.f || use_y != 0.f); + bool has_use_transform = transform_str.len > 0; + + if (has_use_transform) + { + hb_svg_transform_t t; + hb_raster_svg_parse_transform (transform_str, &t); + hb_paint_push_transform (ctx->pfuncs, ctx->paint, t.xx, t.yx, t.xy, t.yy, t.dx, t.dy); + } + + if (has_translate) + hb_paint_push_transform (ctx->pfuncs, ctx->paint, 1, 0, 0, 1, use_x, use_y); + + const char *found = nullptr; + hb_raster_svg_find_element_by_id (ctx->doc_start, ctx->doc_len, ctx->svg_accel, ctx->doc_cache, + ref_id, &found); + + if (found) + { + bool can_render = true; + hb_decycler_node_t node (*ctx->use_decycler); + if (unlikely (!node.visit ((uintptr_t) found))) + can_render = false; + + if (can_render) + { + unsigned remaining = ctx->doc_start + ctx->doc_len - found; + hb_svg_xml_parser_t ref_parser (found, remaining); + hb_svg_token_type_t tok = ref_parser.next (); + if (tok == SVG_TOKEN_OPEN_TAG || tok == SVG_TOKEN_SELF_CLOSE_TAG) + { + bool has_viewport_scale = false; + hb_svg_transform_t t; + if (hb_raster_svg_compute_use_target_viewbox_transform (ref_parser, use_w, use_h, &t)) + { + hb_paint_push_transform (ctx->pfuncs, ctx->paint, t.xx, t.yx, t.xy, t.yy, t.dx, t.dy); + has_viewport_scale = true; + } + render_cb (render_user, ref_parser, state, has_viewport_scale); + if (has_viewport_scale) + hb_paint_pop_transform (ctx->pfuncs, ctx->paint); + } + } + } + + if (has_translate) + hb_paint_pop_transform (ctx->pfuncs, ctx->paint); + + if (has_use_transform) + hb_paint_pop_transform (ctx->pfuncs, ctx->paint); +} diff --git a/src/hb-raster-svg-use.hh b/src/hb-raster-svg-use.hh new file mode 100644 index 000000000..aa81f4a01 --- /dev/null +++ b/src/hb-raster-svg-use.hh @@ -0,0 +1,48 @@ +/* + * Copyright © 2026 Behdad Esfahbod + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Author(s): Behdad Esfahbod + */ + +#ifndef HB_RASTER_SVG_USE_HH +#define HB_RASTER_SVG_USE_HH + +#include "hb.hh" + +#include "hb-raster-svg-context.hh" +#include "hb-raster-svg-parse.hh" + +typedef void (*hb_svg_use_render_cb_t) (void *render_user, + hb_svg_xml_parser_t &parser, + const void *state, + bool viewport_mapped); + +HB_INTERNAL void +hb_raster_svg_render_use_element (const hb_svg_use_context_t *ctx, + hb_svg_xml_parser_t &parser, + const void *state, + hb_svg_str_t transform_str, + hb_svg_use_render_cb_t render_cb, + void *render_user); + +#endif /* HB_RASTER_SVG_USE_HH */ diff --git a/src/hb-raster-svg.cc b/src/hb-raster-svg.cc deleted file mode 100644 index afcd005cb..000000000 --- a/src/hb-raster-svg.cc +++ /dev/null @@ -1,2772 +0,0 @@ -/* - * Copyright © 2026 Behdad Esfahbod - * - * This is part of HarfBuzz, a text shaping library. - * - * Permission is hereby granted, without written agreement and without - * license or royalty fees, to use, copy, modify, and distribute this - * software and its documentation for any purpose, provided that the - * above copyright notice and the following two paragraphs appear in - * all copies of this software. - * - * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR - * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES - * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN - * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH - * DAMAGE. - * - * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, - * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS - * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO - * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. - * - * Author(s): Behdad Esfahbod - */ - -#include "hb.hh" - -#include "hb-face.hh" -#include "hb-raster.h" -#include "hb-raster-paint.hh" -#include "hb-raster-svg.hh" -#include "OT/Color/svg/svg.hh" -#include "hb-draw.h" -#include "hb-ot-color.h" - -#include -#include -#include -#include - - -/* - * 1. String view helper - */ - -struct hb_svg_str_t -{ - const char *data; - unsigned len; - - hb_svg_str_t () : data (nullptr), len (0) {} - hb_svg_str_t (const char *d, unsigned l) : data (d), len (l) {} - - bool is_null () const { return !data; } - - bool eq (const char *s) const - { - unsigned slen = strlen (s); - return len == slen && memcmp (data, s, len) == 0; - } - - bool starts_with (const char *prefix) const - { - unsigned plen = strlen (prefix); - return len >= plen && memcmp (data, prefix, plen) == 0; - } - - bool eq_cstr (const char *s) const - { - unsigned slen = strlen (s); - return len == slen && memcmp (data, s, len) == 0; - } - - float to_float () const - { - if (!data || !len) return 0.f; - /* strtof needs null-terminated string; we use a small stack buffer */ - char buf[64]; - unsigned n = hb_min (len, (unsigned) sizeof (buf) - 1); - memcpy (buf, data, n); - buf[n] = '\0'; - return strtof (buf, nullptr); - } - - int to_int () const - { - if (!data || !len) return 0; - char buf[32]; - unsigned n = hb_min (len, (unsigned) sizeof (buf) - 1); - memcpy (buf, data, n); - buf[n] = '\0'; - return atoi (buf); - } - - /* Skip leading whitespace */ - hb_svg_str_t trim_left () const - { - const char *p = data; - unsigned l = len; - while (l && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) - { p++; l--; } - return {p, l}; - } - - hb_svg_str_t trim () const - { - hb_svg_str_t s = trim_left (); - while (s.len && (s.data[s.len - 1] == ' ' || s.data[s.len - 1] == '\t' || - s.data[s.len - 1] == '\n' || s.data[s.len - 1] == '\r')) - s.len--; - return s; - } -}; - - -/* - * 2. Minimal XML tokenizer - */ - -enum hb_svg_token_type_t -{ - SVG_TOKEN_OPEN_TAG, - SVG_TOKEN_CLOSE_TAG, - SVG_TOKEN_SELF_CLOSE_TAG, - SVG_TOKEN_TEXT, - SVG_TOKEN_EOF -}; - -struct hb_svg_attr_t -{ - hb_svg_str_t name; - hb_svg_str_t value; -}; - -struct hb_svg_xml_parser_t -{ - const char *p; - const char *end; - const char *tag_start = nullptr; - - hb_svg_str_t tag_name; - hb_vector_t attrs; - bool self_closing; - - hb_svg_xml_parser_t (const char *data, unsigned len) - : p (data), end (data + len) {} - - void skip_ws () - { - while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) - p++; - } - - hb_svg_str_t read_name () - { - const char *start = p; - while (p < end && *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r' && - *p != '>' && *p != '/' && *p != '=') - p++; - return {start, (unsigned) (p - start)}; - } - - hb_svg_str_t read_attr_value () - { - if (p >= end) return {}; - char quote = *p; - if (quote != '"' && quote != '\'') return {}; - p++; - const char *start = p; - while (p < end && *p != quote) - p++; - hb_svg_str_t val = {start, (unsigned) (p - start)}; - if (p < end) p++; /* skip closing quote */ - return val; - } - - void parse_attrs () - { - attrs.clear (); - while (p < end) - { - skip_ws (); - if (p >= end || *p == '>' || *p == '/') break; - hb_svg_str_t name = read_name (); - if (!name.len) { p++; continue; } - skip_ws (); - if (p < end && *p == '=') - { - p++; - skip_ws (); - hb_svg_str_t val = read_attr_value (); - hb_svg_attr_t attr = {name, val}; - attrs.push (attr); - } - else - { - hb_svg_attr_t attr = {name, {}}; - attrs.push (attr); - } - } - } - - hb_svg_token_type_t next () - { - while (p < end) - { - if (*p != '<') - { - /* Text content — skip for now */ - while (p < end && *p != '<') p++; - continue; - } - - tag_start = p; - p++; /* skip '<' */ - if (p >= end) return SVG_TOKEN_EOF; - - /* Comment or processing instruction */ - if (*p == '!') - { - /* Skip */ - if (p + 2 < end && p[1] == '-' && p[2] == '-') - { - p += 3; - while (p + 2 < end && !(p[0] == '-' && p[1] == '-' && p[2] == '>')) - p++; - if (p + 2 < end) p += 3; - } - else - { - /* Skip or similar */ - while (p < end && *p != '>') p++; - if (p < end) p++; - } - continue; - } - if (*p == '?') - { - /* */ - while (p + 1 < end && !(p[0] == '?' && p[1] == '>')) - p++; - if (p + 1 < end) p += 2; - continue; - } - - /* Closing tag */ - if (*p == '/') - { - p++; - tag_name = read_name (); - while (p < end && *p != '>') p++; - if (p < end) p++; - attrs.clear (); - self_closing = false; - return SVG_TOKEN_CLOSE_TAG; - } - - /* Opening tag */ - tag_name = read_name (); - parse_attrs (); - - self_closing = false; - skip_ws (); - if (p < end && *p == '/') - { - self_closing = true; - p++; - } - if (p < end && *p == '>') - p++; - - return self_closing ? SVG_TOKEN_SELF_CLOSE_TAG : SVG_TOKEN_OPEN_TAG; - } - return SVG_TOKEN_EOF; - } - - hb_svg_str_t find_attr (const char *name) const - { - for (unsigned i = 0; i < attrs.length; i++) - if (attrs[i].name.eq (name)) - return attrs[i].value; - return {}; - } -}; - - -/* - * 3. SVG Color parser - */ - -struct hb_svg_named_color_t -{ - const char *name; - uint32_t rgb; /* 0xRRGGBB */ -}; - -static const hb_svg_named_color_t svg_named_colors[] = { - {"aliceblue", 0xF0F8FF}, - {"antiquewhite", 0xFAEBD7}, - {"aqua", 0x00FFFF}, - {"aquamarine", 0x7FFFD4}, - {"azure", 0xF0FFFF}, - {"beige", 0xF5F5DC}, - {"bisque", 0xFFE4C4}, - {"black", 0x000000}, - {"blanchedalmond", 0xFFEBCD}, - {"blue", 0x0000FF}, - {"blueviolet", 0x8A2BE2}, - {"brown", 0xA52A2A}, - {"burlywood", 0xDEB887}, - {"cadetblue", 0x5F9EA0}, - {"chartreuse", 0x7FFF00}, - {"chocolate", 0xD2691E}, - {"coral", 0xFF7F50}, - {"cornflowerblue", 0x6495ED}, - {"cornsilk", 0xFFF8DC}, - {"crimson", 0xDC143C}, - {"cyan", 0x00FFFF}, - {"darkblue", 0x00008B}, - {"darkcyan", 0x008B8B}, - {"darkgoldenrod", 0xB8860B}, - {"darkgray", 0xA9A9A9}, - {"darkgreen", 0x006400}, - {"darkgrey", 0xA9A9A9}, - {"darkkhaki", 0xBDB76B}, - {"darkmagenta", 0x8B008B}, - {"darkolivegreen", 0x556B2F}, - {"darkorange", 0xFF8C00}, - {"darkorchid", 0x9932CC}, - {"darkred", 0x8B0000}, - {"darksalmon", 0xE9967A}, - {"darkseagreen", 0x8FBC8F}, - {"darkslateblue", 0x483D8B}, - {"darkslategray", 0x2F4F4F}, - {"darkslategrey", 0x2F4F4F}, - {"darkturquoise", 0x00CED1}, - {"darkviolet", 0x9400D3}, - {"deeppink", 0xFF1493}, - {"deepskyblue", 0x00BFFF}, - {"dimgray", 0x696969}, - {"dimgrey", 0x696969}, - {"dodgerblue", 0x1E90FF}, - {"firebrick", 0xB22222}, - {"floralwhite", 0xFFFAF0}, - {"forestgreen", 0x228B22}, - {"fuchsia", 0xFF00FF}, - {"gainsboro", 0xDCDCDC}, - {"ghostwhite", 0xF8F8FF}, - {"gold", 0xFFD700}, - {"goldenrod", 0xDAA520}, - {"gray", 0x808080}, - {"green", 0x008000}, - {"greenyellow", 0xADFF2F}, - {"grey", 0x808080}, - {"honeydew", 0xF0FFF0}, - {"hotpink", 0xFF69B4}, - {"indianred", 0xCD5C5C}, - {"indigo", 0x4B0082}, - {"ivory", 0xFFFFF0}, - {"khaki", 0xF0E68C}, - {"lavender", 0xE6E6FA}, - {"lavenderblush", 0xFFF0F5}, - {"lawngreen", 0x7CFC00}, - {"lemonchiffon", 0xFFFACD}, - {"lightblue", 0xADD8E6}, - {"lightcoral", 0xF08080}, - {"lightcyan", 0xE0FFFF}, - {"lightgoldenrodyellow", 0xFAFAD2}, - {"lightgray", 0xD3D3D3}, - {"lightgreen", 0x90EE90}, - {"lightgrey", 0xD3D3D3}, - {"lightpink", 0xFFB6C1}, - {"lightsalmon", 0xFFA07A}, - {"lightseagreen", 0x20B2AA}, - {"lightskyblue", 0x87CEFA}, - {"lightslategray", 0x778899}, - {"lightslategrey", 0x778899}, - {"lightsteelblue", 0xB0C4DE}, - {"lightyellow", 0xFFFFE0}, - {"lime", 0x00FF00}, - {"limegreen", 0x32CD32}, - {"linen", 0xFAF0E6}, - {"magenta", 0xFF00FF}, - {"maroon", 0x800000}, - {"mediumaquamarine", 0x66CDAA}, - {"mediumblue", 0x0000CD}, - {"mediumorchid", 0xBA55D3}, - {"mediumpurple", 0x9370DB}, - {"mediumseagreen", 0x3CB371}, - {"mediumslateblue", 0x7B68EE}, - {"mediumspringgreen", 0x00FA9A}, - {"mediumturquoise", 0x48D1CC}, - {"mediumvioletred", 0xC71585}, - {"midnightblue", 0x191970}, - {"mintcream", 0xF5FFFA}, - {"mistyrose", 0xFFE4E1}, - {"moccasin", 0xFFE4B5}, - {"navajowhite", 0xFFDEAD}, - {"navy", 0x000080}, - {"oldlace", 0xFDF5E6}, - {"olive", 0x808000}, - {"olivedrab", 0x6B8E23}, - {"orange", 0xFFA500}, - {"orangered", 0xFF4500}, - {"orchid", 0xDA70D6}, - {"palegoldenrod", 0xEEE8AA}, - {"palegreen", 0x98FB98}, - {"paleturquoise", 0xAFEEEE}, - {"palevioletred", 0xDB7093}, - {"papayawhip", 0xFFEFD5}, - {"peachpuff", 0xFFDAB9}, - {"peru", 0xCD853F}, - {"pink", 0xFFC0CB}, - {"plum", 0xDDA0DD}, - {"powderblue", 0xB0E0E6}, - {"purple", 0x800080}, - {"rebeccapurple", 0x663399}, - {"red", 0xFF0000}, - {"rosybrown", 0xBC8F8F}, - {"royalblue", 0x4169E1}, - {"saddlebrown", 0x8B4513}, - {"salmon", 0xFA8072}, - {"sandybrown", 0xF4A460}, - {"seagreen", 0x2E8B57}, - {"seashell", 0xFFF5EE}, - {"sienna", 0xA0522D}, - {"silver", 0xC0C0C0}, - {"skyblue", 0x87CEEB}, - {"slateblue", 0x6A5ACD}, - {"slategray", 0x708090}, - {"slategrey", 0x708090}, - {"snow", 0xFFFAFA}, - {"springgreen", 0x00FF7F}, - {"steelblue", 0x4682B4}, - {"tan", 0xD2B48C}, - {"teal", 0x008080}, - {"thistle", 0xD8BFD8}, - {"tomato", 0xFF6347}, - {"turquoise", 0x40E0D0}, - {"violet", 0xEE82EE}, - {"wheat", 0xF5DEB3}, - {"white", 0xFFFFFF}, - {"whitesmoke", 0xF5F5F5}, - {"yellow", 0xFFFF00}, - {"yellowgreen", 0x9ACD32}, -}; - -static int -hexval (char c) -{ - if (c >= '0' && c <= '9') return c - '0'; - if (c >= 'a' && c <= 'f') return c - 'a' + 10; - if (c >= 'A' && c <= 'F') return c - 'A' + 10; - return -1; -} - -/* Parse SVG color value; returns HB_COLOR with alpha = 255. - * Sets *is_none if "none". */ -static hb_color_t -svg_parse_color (hb_svg_str_t s, - hb_paint_funcs_t *pfuncs, - void *paint_data, - hb_color_t foreground, - hb_face_t *face, - unsigned palette, - bool *is_none) -{ - *is_none = false; - s = s.trim (); - if (!s.len) { *is_none = true; return HB_COLOR (0, 0, 0, 0); } - - if (s.eq ("none") || s.eq ("transparent")) - { - *is_none = true; - return HB_COLOR (0, 0, 0, 0); - } - - if (s.eq ("currentColor")) - return foreground; - - /* var(--colorN) → CPAL palette color */ - if (s.starts_with ("var(")) - { - const char *p = s.data + 4; - const char *e = s.data + s.len; - while (p < e && *p == ' ') p++; - if (p + 7 < e && p[0] == '-' && p[1] == '-' && p[2] == 'c' && - p[3] == 'o' && p[4] == 'l' && p[5] == 'o' && p[6] == 'r') - { - p += 7; - unsigned color_index = 0; - while (p < e && *p >= '0' && *p <= '9') - color_index = color_index * 10 + (*p++ - '0'); - - hb_color_t palette_color; - if (hb_paint_custom_palette_color (pfuncs, paint_data, color_index, &palette_color)) - return palette_color; - - unsigned count = 1; - hb_ot_color_palette_get_colors (face, palette, color_index, &count, &palette_color); - if (count) - return palette_color; - } - - /* Fallback value after comma: var(--colorN, fallback) */ - p = s.data + 4; - while (p < e && *p != ',') p++; - if (p < e) - { - p++; - while (p < e && *p == ' ') p++; - const char *val_start = p; - /* Find closing paren */ - while (e > val_start && *(e - 1) != ')') e--; - if (e > val_start) e--; - hb_svg_str_t fallback = {val_start, (unsigned) (e - val_start)}; - return svg_parse_color (fallback, pfuncs, paint_data, foreground, face, palette, is_none); - } - - return foreground; - } - - /* #RGB or #RRGGBB */ - if (s.data[0] == '#') - { - if (s.len == 4) /* #RGB */ - { - int r = hexval (s.data[1]); - int g = hexval (s.data[2]); - int b = hexval (s.data[3]); - if (r < 0 || g < 0 || b < 0) return HB_COLOR (0, 0, 0, 255); - return HB_COLOR (b * 17, g * 17, r * 17, 255); - } - if (s.len == 7) /* #RRGGBB */ - { - int r = hexval (s.data[1]) * 16 + hexval (s.data[2]); - int g = hexval (s.data[3]) * 16 + hexval (s.data[4]); - int b = hexval (s.data[5]) * 16 + hexval (s.data[6]); - return HB_COLOR (b, g, r, 255); - } - return HB_COLOR (0, 0, 0, 255); - } - - /* rgb(r, g, b) or rgb(r%, g%, b%) */ - if (s.starts_with ("rgb")) - { - const char *p = s.data + 3; - const char *e = s.data + s.len; - while (p < e && *p != '(') p++; - if (p < e) p++; - - auto read_component = [&] () -> int { - while (p < e && (*p == ' ' || *p == ',')) p++; - char buf[32]; - unsigned n = 0; - while (p < e && n < sizeof (buf) - 1 && ((*p >= '0' && *p <= '9') || *p == '.' || *p == '-')) - buf[n++] = *p++; - bool is_pct = (p < e && *p == '%'); - if (is_pct) p++; - buf[n] = '\0'; - float val = strtof (buf, nullptr); - if (is_pct) val = val * 255.f / 100.f; - return hb_clamp ((int) (val + 0.5f), 0, 255); - }; - - int r = read_component (); - int g = read_component (); - int b = read_component (); - return HB_COLOR (b, g, r, 255); - } - - /* Named colors (case-insensitive comparison) */ - { - char lower[32]; - unsigned n = hb_min (s.len, (unsigned) sizeof (lower) - 1); - for (unsigned i = 0; i < n; i++) - lower[i] = (s.data[i] >= 'A' && s.data[i] <= 'Z') ? s.data[i] + 32 : s.data[i]; - lower[n] = '\0'; - - for (unsigned i = 0; i < ARRAY_LENGTH (svg_named_colors); i++) - if (strcmp (lower, svg_named_colors[i].name) == 0) - { - uint32_t rgb = svg_named_colors[i].rgb; - return HB_COLOR (rgb & 0xFF, (rgb >> 8) & 0xFF, (rgb >> 16) & 0xFF, 255); - } - } - - return HB_COLOR (0, 0, 0, 255); -} - - -/* - * 4. SVG Number/Float parser - */ - -struct hb_svg_float_parser_t -{ - const char *p; - const char *end; - - hb_svg_float_parser_t (hb_svg_str_t s) : p (s.data), end (s.data + s.len) {} - hb_svg_float_parser_t (const char *d, unsigned l) : p (d), end (d + l) {} - - void skip_ws_comma () - { - while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || *p == ',')) - p++; - } - - bool has_more () const { return p < end; } - - float next_float () - { - skip_ws_comma (); - if (p >= end) return 0.f; - char buf[64]; - unsigned n = 0; - if (p < end && (*p == '-' || *p == '+')) - buf[n++] = *p++; - while (p < end && n < sizeof (buf) - 1 && *p >= '0' && *p <= '9') - buf[n++] = *p++; - if (p < end && n < sizeof (buf) - 1 && *p == '.') - { - buf[n++] = *p++; - while (p < end && n < sizeof (buf) - 1 && *p >= '0' && *p <= '9') - buf[n++] = *p++; - } - if (p < end && n < sizeof (buf) - 1 && (*p == 'e' || *p == 'E')) - { - buf[n++] = *p++; - if (p < end && n < sizeof (buf) - 1 && (*p == '+' || *p == '-')) - buf[n++] = *p++; - while (p < end && n < sizeof (buf) - 1 && *p >= '0' && *p <= '9') - buf[n++] = *p++; - } - buf[n] = '\0'; - return strtof (buf, nullptr); - } - - int next_int () - { - return (int) next_float (); - } - - bool next_flag () - { - skip_ws_comma (); - if (p >= end) return false; - bool v = *p != '0'; - p++; - return v; - } -}; - -static float -svg_parse_float (hb_svg_str_t s) -{ - return s.to_float (); -} - - - -/* - * 5. SVG Transform parser - */ - -struct hb_svg_transform_t -{ - float xx = 1, yx = 0, xy = 0, yy = 1, dx = 0, dy = 0; - - void multiply (const hb_svg_transform_t &other) - { - float nxx = xx * other.xx + xy * other.yx; - float nyx = yx * other.xx + yy * other.yx; - float nxy = xx * other.xy + xy * other.yy; - float nyy = yx * other.xy + yy * other.yy; - float ndx = xx * other.dx + xy * other.dy + dx; - float ndy = yx * other.dx + yy * other.dy + dy; - xx = nxx; yx = nyx; xy = nxy; yy = nyy; dx = ndx; dy = ndy; - } -}; - -static bool -svg_parse_transform (hb_svg_str_t s, hb_svg_transform_t *out) -{ - hb_svg_float_parser_t fp (s); - - while (fp.p < fp.end) - { - fp.skip_ws_comma (); - if (fp.p >= fp.end) break; - - const char *start = fp.p; - /* Read function name */ - while (fp.p < fp.end && *fp.p != '(') fp.p++; - hb_svg_str_t func_name = {start, (unsigned) (fp.p - start)}; - - /* Trim trailing whitespace from function name */ - while (func_name.len && (func_name.data[func_name.len - 1] == ' ' || - func_name.data[func_name.len - 1] == '\t')) - func_name.len--; - - if (fp.p >= fp.end) break; - fp.p++; /* skip '(' */ - - hb_svg_transform_t t; - - if (func_name.eq ("matrix")) - { - t.xx = fp.next_float (); - t.yx = fp.next_float (); - t.xy = fp.next_float (); - t.yy = fp.next_float (); - t.dx = fp.next_float (); - t.dy = fp.next_float (); - } - else if (func_name.eq ("translate")) - { - t.dx = fp.next_float (); - fp.skip_ws_comma (); - if (fp.p < fp.end && *fp.p != ')') - t.dy = fp.next_float (); - } - else if (func_name.eq ("scale")) - { - t.xx = fp.next_float (); - fp.skip_ws_comma (); - if (fp.p < fp.end && *fp.p != ')') - t.yy = fp.next_float (); - else - t.yy = t.xx; - } - else if (func_name.eq ("rotate")) - { - float angle = fp.next_float () * (float) M_PI / 180.f; - float cs = cosf (angle), sn = sinf (angle); - fp.skip_ws_comma (); - if (fp.p < fp.end && *fp.p != ')') - { - float cx = fp.next_float (); - float cy = fp.next_float (); - t.xx = cs; t.yx = sn; - t.xy = -sn; t.yy = cs; - t.dx = cx - cs * cx + sn * cy; - t.dy = cy - sn * cx - cs * cy; - } - else - { - t.xx = cs; t.yx = sn; - t.xy = -sn; t.yy = cs; - } - } - else if (func_name.eq ("skewX")) - { - float angle = fp.next_float () * (float) M_PI / 180.f; - t.xy = tanf (angle); - } - else if (func_name.eq ("skewY")) - { - float angle = fp.next_float () * (float) M_PI / 180.f; - t.yx = tanf (angle); - } - - /* Skip to closing ')' */ - while (fp.p < fp.end && *fp.p != ')') fp.p++; - if (fp.p < fp.end) fp.p++; - - out->multiply (t); - } - return true; -} - - -/* - * 6. SVG Path Data parser - */ - -static void -svg_arc_to_cubics (hb_draw_funcs_t *dfuncs, void *draw_data, hb_draw_state_t *st, - float cx, float cy, - float rx, float ry, - float phi, float theta1, float dtheta) -{ - /* Approximate arc with cubic bezier segments. - * Split into segments of at most 90 degrees. */ - int n_segs = (int) ceilf (fabsf (dtheta) / ((float) M_PI / 2.f)); - if (n_segs < 1) n_segs = 1; - float seg_angle = dtheta / n_segs; - - float cos_phi = cosf (phi); - float sin_phi = sinf (phi); - - for (int i = 0; i < n_segs; i++) - { - float t1 = theta1 + i * seg_angle; - float t2 = t1 + seg_angle; - float alpha = sinf (seg_angle) * (sqrtf (4.f + 3.f * tanf (seg_angle / 2.f) * tanf (seg_angle / 2.f)) - 1.f) / 3.f; - - float cos_t1 = cosf (t1), sin_t1 = sinf (t1); - float cos_t2 = cosf (t2), sin_t2 = sinf (t2); - - /* Endpoint 1 (on unit circle) */ - float e1x = rx * cos_t1, e1y = ry * sin_t1; - /* Endpoint 2 */ - float e2x = rx * cos_t2, e2y = ry * sin_t2; - /* Derivative at t1 */ - float d1x = -rx * sin_t1, d1y = ry * cos_t1; - /* Derivative at t2 */ - float d2x = -rx * sin_t2, d2y = ry * cos_t2; - - /* Control points */ - float cp1x = e1x + alpha * d1x; - float cp1y = e1y + alpha * d1y; - float cp2x = e2x - alpha * d2x; - float cp2y = e2y - alpha * d2y; - - /* Rotate and translate */ - float r_cp1x = cos_phi * cp1x - sin_phi * cp1y + cx; - float r_cp1y = sin_phi * cp1x + cos_phi * cp1y + cy; - float r_cp2x = cos_phi * cp2x - sin_phi * cp2y + cx; - float r_cp2y = sin_phi * cp2x + cos_phi * cp2y + cy; - float r_e2x = cos_phi * e2x - sin_phi * e2y + cx; - float r_e2y = sin_phi * e2x + cos_phi * e2y + cy; - - hb_draw_cubic_to (dfuncs, draw_data, st, - r_cp1x, r_cp1y, - r_cp2x, r_cp2y, - r_e2x, r_e2y); - } -} - -static void -svg_arc_endpoint_to_center (float x1, float y1, float x2, float y2, - float rx, float ry, float phi_deg, - bool large_arc, bool sweep, - float *cx_out, float *cy_out, - float *theta1_out, float *dtheta_out, - float *rx_out, float *ry_out) -{ - float phi = phi_deg * (float) M_PI / 180.f; - float cos_phi = cosf (phi), sin_phi = sinf (phi); - - /* Step 1: compute (x1', y1') */ - float mx = (x1 - x2) / 2.f; - float my = (y1 - y2) / 2.f; - float x1p = cos_phi * mx + sin_phi * my; - float y1p = -sin_phi * mx + cos_phi * my; - - /* Correct radii */ - rx = fabsf (rx); ry = fabsf (ry); - if (rx < 1e-10f || ry < 1e-10f) - { - *cx_out = (x1 + x2) / 2.f; - *cy_out = (y1 + y2) / 2.f; - *theta1_out = 0; - *dtheta_out = 0; - *rx_out = rx; *ry_out = ry; - return; - } - - float x1p2 = x1p * x1p, y1p2 = y1p * y1p; - float rx2 = rx * rx, ry2 = ry * ry; - float lambda = x1p2 / rx2 + y1p2 / ry2; - if (lambda > 1.f) - { - float sl = sqrtf (lambda); - rx *= sl; ry *= sl; - rx2 = rx * rx; ry2 = ry * ry; - } - - /* Step 2: compute (cx', cy') */ - float num = rx2 * ry2 - rx2 * y1p2 - ry2 * x1p2; - float den = rx2 * y1p2 + ry2 * x1p2; - float sq = (den > 0.f) ? sqrtf (hb_max (num / den, 0.f)) : 0.f; - if (large_arc == sweep) sq = -sq; - - float cxp = sq * rx * y1p / ry; - float cyp = -sq * ry * x1p / rx; - - /* Step 3: compute (cx, cy) */ - float cx = cos_phi * cxp - sin_phi * cyp + (x1 + x2) / 2.f; - float cy = sin_phi * cxp + cos_phi * cyp + (y1 + y2) / 2.f; - - /* Step 4: compute theta1 and dtheta */ - auto angle = [] (float ux, float uy, float vx, float vy) -> float { - float dot = ux * vx + uy * vy; - float len = sqrtf ((ux * ux + uy * uy) * (vx * vx + vy * vy)); - float a = acosf (hb_clamp (dot / len, -1.f, 1.f)); - if (ux * vy - uy * vx < 0.f) a = -a; - return a; - }; - - float theta1 = angle (1.f, 0.f, (x1p - cxp) / rx, (y1p - cyp) / ry); - float dtheta = angle ((x1p - cxp) / rx, (y1p - cyp) / ry, - (-x1p - cxp) / rx, (-y1p - cyp) / ry); - - if (!sweep && dtheta > 0.f) dtheta -= 2.f * (float) M_PI; - if (sweep && dtheta < 0.f) dtheta += 2.f * (float) M_PI; - - *cx_out = cx; *cy_out = cy; - *theta1_out = theta1; *dtheta_out = dtheta; - *rx_out = rx; *ry_out = ry; -} - -static void -svg_parse_path_data (hb_svg_str_t d, hb_draw_funcs_t *dfuncs, void *draw_data) -{ - hb_draw_state_t st = HB_DRAW_STATE_DEFAULT; - hb_svg_float_parser_t fp (d); - - float cur_x = 0, cur_y = 0; - float start_x = 0, start_y = 0; - float last_cx = 0, last_cy = 0; /* for S/T smooth curves */ - char last_cmd = 0; - char cmd = 0; - - while (fp.p < fp.end) - { - fp.skip_ws_comma (); - if (fp.p >= fp.end) break; - - /* Check if next char is a command letter */ - char c = *fp.p; - if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) - { - cmd = c; - fp.p++; - } - /* else repeat previous command with new parameters */ - - switch (cmd) - { - case 'M': case 'm': - { - float x = fp.next_float (); - float y = fp.next_float (); - if (cmd == 'm') { x += cur_x; y += cur_y; } - hb_draw_move_to (dfuncs, draw_data, &st, x, y); - cur_x = start_x = x; - cur_y = start_y = y; - /* Subsequent coordinates after M are treated as L */ - cmd = (cmd == 'M') ? 'L' : 'l'; - last_cmd = 'M'; - continue; - } - case 'L': case 'l': - { - float x = fp.next_float (); - float y = fp.next_float (); - if (cmd == 'l') { x += cur_x; y += cur_y; } - hb_draw_line_to (dfuncs, draw_data, &st, x, y); - cur_x = x; cur_y = y; - break; - } - case 'H': case 'h': - { - float x = fp.next_float (); - if (cmd == 'h') x += cur_x; - hb_draw_line_to (dfuncs, draw_data, &st, x, cur_y); - cur_x = x; - break; - } - case 'V': case 'v': - { - float y = fp.next_float (); - if (cmd == 'v') y += cur_y; - hb_draw_line_to (dfuncs, draw_data, &st, cur_x, y); - cur_y = y; - break; - } - case 'C': case 'c': - { - float x1 = fp.next_float (); - float y1 = fp.next_float (); - float x2 = fp.next_float (); - float y2 = fp.next_float (); - float x = fp.next_float (); - float y = fp.next_float (); - if (cmd == 'c') - { x1 += cur_x; y1 += cur_y; x2 += cur_x; y2 += cur_y; x += cur_x; y += cur_y; } - hb_draw_cubic_to (dfuncs, draw_data, &st, x1, y1, x2, y2, x, y); - last_cx = x2; last_cy = y2; - cur_x = x; cur_y = y; - break; - } - case 'S': case 's': - { - float cx1, cy1; - if (last_cmd == 'C' || last_cmd == 'c' || last_cmd == 'S' || last_cmd == 's') - { cx1 = 2 * cur_x - last_cx; cy1 = 2 * cur_y - last_cy; } - else - { cx1 = cur_x; cy1 = cur_y; } - float x2 = fp.next_float (); - float y2 = fp.next_float (); - float x = fp.next_float (); - float y = fp.next_float (); - if (cmd == 's') - { x2 += cur_x; y2 += cur_y; x += cur_x; y += cur_y; } - hb_draw_cubic_to (dfuncs, draw_data, &st, cx1, cy1, x2, y2, x, y); - last_cx = x2; last_cy = y2; - cur_x = x; cur_y = y; - break; - } - case 'Q': case 'q': - { - float x1 = fp.next_float (); - float y1 = fp.next_float (); - float x = fp.next_float (); - float y = fp.next_float (); - if (cmd == 'q') - { x1 += cur_x; y1 += cur_y; x += cur_x; y += cur_y; } - hb_draw_quadratic_to (dfuncs, draw_data, &st, x1, y1, x, y); - last_cx = x1; last_cy = y1; - cur_x = x; cur_y = y; - break; - } - case 'T': case 't': - { - float cx1, cy1; - if (last_cmd == 'Q' || last_cmd == 'q' || last_cmd == 'T' || last_cmd == 't') - { cx1 = 2 * cur_x - last_cx; cy1 = 2 * cur_y - last_cy; } - else - { cx1 = cur_x; cy1 = cur_y; } - float x = fp.next_float (); - float y = fp.next_float (); - if (cmd == 't') { x += cur_x; y += cur_y; } - hb_draw_quadratic_to (dfuncs, draw_data, &st, cx1, cy1, x, y); - last_cx = cx1; last_cy = cy1; - cur_x = x; cur_y = y; - break; - } - case 'A': case 'a': - { - float rx = fp.next_float (); - float ry = fp.next_float (); - float x_rot = fp.next_float (); - bool large_arc = fp.next_flag (); - bool sweep = fp.next_flag (); - float x = fp.next_float (); - float y = fp.next_float (); - if (cmd == 'a') { x += cur_x; y += cur_y; } - - if (fabsf (x - cur_x) < 1e-6f && fabsf (y - cur_y) < 1e-6f) - { - cur_x = x; cur_y = y; - break; - } - - float cx, cy, theta1, dtheta, adj_rx, adj_ry; - svg_arc_endpoint_to_center (cur_x, cur_y, x, y, - rx, ry, x_rot, - large_arc, sweep, - &cx, &cy, &theta1, &dtheta, - &adj_rx, &adj_ry); - - float phi = x_rot * (float) M_PI / 180.f; - svg_arc_to_cubics (dfuncs, draw_data, &st, - cx, cy, adj_rx, adj_ry, phi, theta1, dtheta); - cur_x = x; cur_y = y; - break; - } - case 'Z': case 'z': - hb_draw_close_path (dfuncs, draw_data, &st); - cur_x = start_x; - cur_y = start_y; - break; - - default: - /* Unknown command, skip a character */ - fp.p++; - continue; - } - - last_cmd = cmd; - } -} - - -/* - * 7. Shape-to-path converters - */ - -static void -svg_rect_to_path (float x, float y, float w, float h, float rx, float ry, - hb_draw_funcs_t *dfuncs, void *draw_data) -{ - hb_draw_state_t st = HB_DRAW_STATE_DEFAULT; - - if (rx <= 0 && ry <= 0) - { - /* Simple rectangle */ - hb_draw_move_to (dfuncs, draw_data, &st, x, y); - hb_draw_line_to (dfuncs, draw_data, &st, x + w, y); - hb_draw_line_to (dfuncs, draw_data, &st, x + w, y + h); - hb_draw_line_to (dfuncs, draw_data, &st, x, y + h); - hb_draw_close_path (dfuncs, draw_data, &st); - return; - } - - /* Rounded rectangle */ - if (rx <= 0) rx = ry; - if (ry <= 0) ry = rx; - rx = hb_min (rx, w / 2); - ry = hb_min (ry, h / 2); - - /* Kappa for circular arcs approximated by cubic bezier */ - float kx = rx * 0.5522847498f; - float ky = ry * 0.5522847498f; - - hb_draw_move_to (dfuncs, draw_data, &st, x + rx, y); - hb_draw_line_to (dfuncs, draw_data, &st, x + w - rx, y); - hb_draw_cubic_to (dfuncs, draw_data, &st, - x + w - rx + kx, y, - x + w, y + ry - ky, - x + w, y + ry); - hb_draw_line_to (dfuncs, draw_data, &st, x + w, y + h - ry); - hb_draw_cubic_to (dfuncs, draw_data, &st, - x + w, y + h - ry + ky, - x + w - rx + kx, y + h, - x + w - rx, y + h); - hb_draw_line_to (dfuncs, draw_data, &st, x + rx, y + h); - hb_draw_cubic_to (dfuncs, draw_data, &st, - x + rx - kx, y + h, - x, y + h - ry + ky, - x, y + h - ry); - hb_draw_line_to (dfuncs, draw_data, &st, x, y + ry); - hb_draw_cubic_to (dfuncs, draw_data, &st, - x, y + ry - ky, - x + rx - kx, y, - x + rx, y); - hb_draw_close_path (dfuncs, draw_data, &st); -} - -static void -svg_circle_to_path (float cx, float cy, float r, - hb_draw_funcs_t *dfuncs, void *draw_data) -{ - hb_draw_state_t st = HB_DRAW_STATE_DEFAULT; - float k = r * 0.5522847498f; - - hb_draw_move_to (dfuncs, draw_data, &st, cx + r, cy); - hb_draw_cubic_to (dfuncs, draw_data, &st, - cx + r, cy + k, - cx + k, cy + r, - cx, cy + r); - hb_draw_cubic_to (dfuncs, draw_data, &st, - cx - k, cy + r, - cx - r, cy + k, - cx - r, cy); - hb_draw_cubic_to (dfuncs, draw_data, &st, - cx - r, cy - k, - cx - k, cy - r, - cx, cy - r); - hb_draw_cubic_to (dfuncs, draw_data, &st, - cx + k, cy - r, - cx + r, cy - k, - cx + r, cy); - hb_draw_close_path (dfuncs, draw_data, &st); -} - -static void -svg_ellipse_to_path (float cx, float cy, float rx, float ry, - hb_draw_funcs_t *dfuncs, void *draw_data) -{ - hb_draw_state_t st = HB_DRAW_STATE_DEFAULT; - float kx = rx * 0.5522847498f; - float ky = ry * 0.5522847498f; - - hb_draw_move_to (dfuncs, draw_data, &st, cx + rx, cy); - hb_draw_cubic_to (dfuncs, draw_data, &st, - cx + rx, cy + ky, - cx + kx, cy + ry, - cx, cy + ry); - hb_draw_cubic_to (dfuncs, draw_data, &st, - cx - kx, cy + ry, - cx - rx, cy + ky, - cx - rx, cy); - hb_draw_cubic_to (dfuncs, draw_data, &st, - cx - rx, cy - ky, - cx - kx, cy - ry, - cx, cy - ry); - hb_draw_cubic_to (dfuncs, draw_data, &st, - cx + kx, cy - ry, - cx + rx, cy - ky, - cx + rx, cy); - hb_draw_close_path (dfuncs, draw_data, &st); -} - -static void -svg_line_to_path (float x1, float y1, float x2, float y2, - hb_draw_funcs_t *dfuncs, void *draw_data) -{ - hb_draw_state_t st = HB_DRAW_STATE_DEFAULT; - hb_draw_move_to (dfuncs, draw_data, &st, x1, y1); - hb_draw_line_to (dfuncs, draw_data, &st, x2, y2); -} - -static void -svg_polygon_to_path (hb_svg_str_t points, bool close, - hb_draw_funcs_t *dfuncs, void *draw_data) -{ - hb_draw_state_t st = HB_DRAW_STATE_DEFAULT; - hb_svg_float_parser_t fp (points); - bool first = true; - while (fp.has_more ()) - { - float x = fp.next_float (); - float y = fp.next_float (); - if (first) - { - hb_draw_move_to (dfuncs, draw_data, &st, x, y); - first = false; - } - else - hb_draw_line_to (dfuncs, draw_data, &st, x, y); - } - if (close && !first) - hb_draw_close_path (dfuncs, draw_data, &st); -} - - -/* - * 8. Shape descriptor - */ - -struct hb_svg_shape_emit_data_t -{ - enum { SHAPE_PATH, SHAPE_RECT, SHAPE_CIRCLE, SHAPE_ELLIPSE, - SHAPE_LINE, SHAPE_POLYLINE, SHAPE_POLYGON } type; - hb_svg_str_t str_data; /* for path 'd' or polyline/polygon 'points' */ - float params[6]; /* for rect/circle/ellipse/line */ -}; - - -/* - * 9. Defs store - */ - -enum hb_svg_gradient_type_t -{ - SVG_GRADIENT_LINEAR, - SVG_GRADIENT_RADIAL -}; - -struct hb_svg_gradient_stop_t -{ - float offset; - hb_color_t color; -}; - -struct hb_svg_gradient_t -{ - hb_svg_gradient_type_t type; - - /* Common */ - hb_paint_extend_t spread = HB_PAINT_EXTEND_PAD; - bool has_spread = false; - hb_svg_transform_t gradient_transform; - bool has_gradient_transform = false; - bool units_user_space = false; /* false = objectBoundingBox (default) */ - bool has_units_user_space = false; - - /* Linear gradient: x1, y1, x2, y2 */ - float x1 = 0, y1 = 0, x2 = 1, y2 = 0; - bool has_x1 = false, has_y1 = false, has_x2 = false, has_y2 = false; - - /* Radial gradient: cx, cy, r, fx, fy */ - float cx = 0.5f, cy = 0.5f, r = 0.5f; - float fx = -1.f, fy = -1.f; /* -1 = not set, use cx/cy */ - bool has_cx = false, has_cy = false, has_r = false; - bool has_fx = false, has_fy = false; - - hb_vector_t stops; - - /* href reference to another gradient */ - char href_id[64] = {}; -}; - -struct hb_svg_clip_path_def_t -{ - unsigned first_shape = 0; - unsigned shape_count = 0; - hb_svg_transform_t clip_transform; - bool has_clip_transform = false; - bool units_user_space = true; /* default per SVG */ -}; - -struct hb_svg_clip_shape_t -{ - hb_svg_shape_emit_data_t shape; - hb_svg_transform_t transform; - bool has_transform = false; -}; - -struct hb_svg_def_t -{ - char id[64]; - enum { DEF_GRADIENT, DEF_CLIP_PATH, DEF_ELEMENT } type; - unsigned index; /* index into respective array */ -}; - -struct hb_svg_defs_t -{ - hb_vector_t gradients; - hb_vector_t clip_shapes; - hb_vector_t clip_paths; - hb_vector_t defs; - - bool add_gradient (const char *id, const hb_svg_gradient_t &grad) - { - unsigned idx = gradients.length; - gradients.push (grad); - if (unlikely (gradients.in_error ())) - return false; - - hb_svg_def_t def; - unsigned n = hb_min (strlen (id), (size_t) sizeof (def.id) - 1); - memcpy (def.id, id, n); - def.id[n] = '\0'; - def.type = hb_svg_def_t::DEF_GRADIENT; - def.index = idx; - defs.push (def); - if (unlikely (defs.in_error ())) - { - gradients.pop (); - return false; - } - return true; - } - - const hb_svg_gradient_t *find_gradient (const char *id) const - { - for (unsigned i = 0; i < defs.length; i++) - if (defs[i].type == hb_svg_def_t::DEF_GRADIENT && - strcmp (defs[i].id, id) == 0) - return &gradients[defs[i].index]; - return nullptr; - } - - bool add_clip_path (const char *id, const hb_svg_clip_path_def_t &clip) - { - unsigned idx = clip_paths.length; - clip_paths.push (clip); - if (unlikely (clip_paths.in_error ())) - return false; - - hb_svg_def_t def; - unsigned n = hb_min (strlen (id), (size_t) sizeof (def.id) - 1); - memcpy (def.id, id, n); - def.id[n] = '\0'; - def.type = hb_svg_def_t::DEF_CLIP_PATH; - def.index = idx; - defs.push (def); - if (unlikely (defs.in_error ())) - { - clip_paths.pop (); - return false; - } - return true; - } - - const hb_svg_clip_path_def_t *find_clip_path (const char *id) const - { - for (unsigned i = 0; i < defs.length; i++) - if (defs[i].type == hb_svg_def_t::DEF_CLIP_PATH && - strcmp (defs[i].id, id) == 0) - return &clip_paths[defs[i].index]; - return nullptr; - } - - const hb_svg_clip_path_def_t *find_clip_path_str (hb_svg_str_t s) const - { - char id[64]; - if (!parse_paint_server_id (s, id)) - return nullptr; - return find_clip_path (id); - } - - const hb_svg_gradient_t *find_gradient_str (hb_svg_str_t s) const - { - char id[64]; - if (!parse_paint_server_id (s, id)) - return nullptr; - return find_gradient (id); - } - - static bool parse_paint_server_id (hb_svg_str_t s, char out[64]) - { - if (!s.starts_with ("url(")) - return false; - - const char *p = s.data + 4; - const char *e = s.data + s.len; - while (p < e && *p == ' ') p++; - if (p < e && *p == '#') p++; - const char *start = p; - while (p < e && *p != ')') p++; - unsigned n = hb_min ((unsigned) (p - start), (unsigned) 63); - memcpy (out, start, n); - out[n] = '\0'; - return true; - } - - static bool parse_fragment_id (hb_svg_str_t s, char out[64]) - { - s = s.trim (); - if (!s.len || s.data[0] != '#') - return false; - - unsigned n = hb_min (s.len - 1, (unsigned) 63); - memcpy (out, s.data + 1, n); - out[n] = '\0'; - return true; - } -}; - - -/* - * 10. Gradient handler — construct hb_color_line_t - */ - -struct hb_svg_color_line_data_t -{ - const hb_svg_gradient_t *grad; - hb_paint_extend_t extend; - float alpha_scale; -}; - -static unsigned -svg_color_line_get_stops (hb_color_line_t *color_line HB_UNUSED, - void *color_line_data, - unsigned int start, - unsigned int *count, - hb_color_stop_t *color_stops, - void *user_data HB_UNUSED) -{ - hb_svg_color_line_data_t *cl = (hb_svg_color_line_data_t *) color_line_data; - const hb_svg_gradient_t *grad = cl->grad; - unsigned total = grad->stops.length; - - if (count) - { - unsigned n = hb_min (*count, total > start ? total - start : 0u); - for (unsigned i = 0; i < n; i++) - { - color_stops[i].offset = grad->stops[start + i].offset; - color_stops[i].is_foreground = false; - hb_color_t c = grad->stops[start + i].color; - if (cl->alpha_scale < 1.f) - { - uint8_t a = (uint8_t) hb_clamp ((int) (hb_color_get_alpha (c) * cl->alpha_scale + 0.5f), 0, 255); - c = HB_COLOR (hb_color_get_blue (c), - hb_color_get_green (c), - hb_color_get_red (c), - a); - } - color_stops[i].color = c; - } - *count = n; - } - return total; -} - -static hb_paint_extend_t -svg_color_line_get_extend (hb_color_line_t *color_line HB_UNUSED, - void *color_line_data, - void *user_data HB_UNUSED) -{ - hb_svg_color_line_data_t *cl = (hb_svg_color_line_data_t *) color_line_data; - return cl->extend; -} - - -/* - * 11. SVG rendering context - */ - -#define SVG_MAX_DEPTH 32 - -struct hb_svg_render_context_t -{ - hb_raster_paint_t *paint; - hb_paint_funcs_t *pfuncs; - hb_font_t *font; - unsigned palette; - hb_color_t foreground; - hb_svg_defs_t defs; - int depth = 0; - - /* The full SVG document for resolution */ - const char *doc_start; - unsigned doc_len; - const OT::SVG::accelerator_t *svg_accel = nullptr; - const OT::SVG::svg_doc_cache_t *doc_cache = nullptr; - - void push_transform (float xx, float yx, float xy, float yy, float dx, float dy) - { - hb_paint_push_transform (pfuncs, paint, xx, yx, xy, yy, dx, dy); - } - void pop_transform () - { - hb_paint_pop_transform (pfuncs, paint); - } - void push_group () - { - hb_paint_push_group (pfuncs, paint); - } - void pop_group (hb_paint_composite_mode_t mode) - { - hb_paint_pop_group (pfuncs, paint, mode); - } - void paint_color (hb_color_t color) - { - hb_paint_color (pfuncs, paint, false, color); - } - void pop_clip () - { - hb_paint_pop_clip (pfuncs, paint); - } -}; - - -/* - * Emit fill (solid or gradient) - */ - -static void -svg_emit_fill (hb_svg_render_context_t *ctx, - hb_svg_str_t fill_str, - float fill_opacity, - const hb_extents_t<> *object_bbox) -{ - bool is_none = false; - - /* Check for gradient reference */ - const hb_svg_gradient_t *grad = ctx->defs.find_gradient_str (fill_str); - if (grad) - { - /* Resolve href chain and inherit unspecified attributes from references. */ - const hb_svg_gradient_t *chain[8]; - unsigned chain_len = 0; - const hb_svg_gradient_t *cur = grad; - while (cur && chain_len < ARRAY_LENGTH (chain)) - { - chain[chain_len++] = cur; - if (!cur->href_id[0]) break; - const hb_svg_gradient_t *next = ctx->defs.find_gradient (cur->href_id); - if (!next) break; - bool is_cycle = false; - for (unsigned i = 0; i < chain_len; i++) - if (chain[i] == next) - { - is_cycle = true; - break; - } - if (is_cycle) break; - cur = next; - } - if (!chain_len) return; - - hb_svg_gradient_t effective = *chain[chain_len - 1]; - for (int i = (int) chain_len - 2; i >= 0; i--) - { - const hb_svg_gradient_t *g = chain[i]; - effective.type = g->type; - if (g->stops.length) effective.stops = g->stops; - if (g->has_spread) { effective.spread = g->spread; effective.has_spread = true; } - if (g->has_units_user_space) - { - effective.units_user_space = g->units_user_space; - effective.has_units_user_space = true; - } - if (g->has_gradient_transform) - { - effective.gradient_transform = g->gradient_transform; - effective.has_gradient_transform = true; - } - if (g->has_x1) { effective.x1 = g->x1; effective.has_x1 = true; } - if (g->has_y1) { effective.y1 = g->y1; effective.has_y1 = true; } - if (g->has_x2) { effective.x2 = g->x2; effective.has_x2 = true; } - if (g->has_y2) { effective.y2 = g->y2; effective.has_y2 = true; } - if (g->has_cx) { effective.cx = g->cx; effective.has_cx = true; } - if (g->has_cy) { effective.cy = g->cy; effective.has_cy = true; } - if (g->has_r) { effective.r = g->r; effective.has_r = true; } - if (g->has_fx) { effective.fx = g->fx; effective.has_fx = true; } - if (g->has_fy) { effective.fy = g->fy; effective.has_fy = true; } - } - if (!effective.stops.length) - return; - - hb_svg_color_line_data_t cl_data; - cl_data.grad = &effective; - cl_data.extend = effective.spread; - cl_data.alpha_scale = hb_clamp (fill_opacity, 0.f, 1.f); - - hb_color_line_t cl = { - &cl_data, - svg_color_line_get_stops, nullptr, - svg_color_line_get_extend, nullptr - }; - - bool has_bbox_transform = !effective.units_user_space && object_bbox && !object_bbox->is_empty (); - if (has_bbox_transform) - { - float w = object_bbox->xmax - object_bbox->xmin; - float h = object_bbox->ymax - object_bbox->ymin; - if (w > 0 && h > 0) - ctx->push_transform (w, 0, 0, h, object_bbox->xmin, object_bbox->ymin); - else - has_bbox_transform = false; - } - - if (effective.has_gradient_transform) - ctx->push_transform (effective.gradient_transform.xx, - effective.gradient_transform.yx, - effective.gradient_transform.xy, - effective.gradient_transform.yy, - effective.gradient_transform.dx, - effective.gradient_transform.dy); - - if (effective.type == SVG_GRADIENT_LINEAR) - { - hb_paint_linear_gradient (ctx->pfuncs, ctx->paint, &cl, - effective.x1, effective.y1, - effective.x2, effective.y2, - effective.x2 - (effective.y2 - effective.y1), - effective.y2 + (effective.x2 - effective.x1)); - } - else /* SVG_GRADIENT_RADIAL */ - { - float fx = effective.has_fx ? effective.fx : effective.cx; - float fy = effective.has_fy ? effective.fy : effective.cy; - - hb_paint_radial_gradient (ctx->pfuncs, ctx->paint, &cl, - fx, fy, 0.f, - effective.cx, effective.cy, effective.r); - } - - if (effective.has_gradient_transform) - ctx->pop_transform (); - if (has_bbox_transform) - ctx->pop_transform (); - - return; - } - - /* Solid color */ - hb_color_t color = svg_parse_color (fill_str, - ctx->pfuncs, - ctx->paint, - ctx->foreground, - hb_font_get_face (ctx->font), - ctx->palette, - &is_none); - if (is_none) return; - - if (fill_opacity < 1.f) - color = HB_COLOR (hb_color_get_blue (color), - hb_color_get_green (color), - hb_color_get_red (color), - (uint8_t) (hb_color_get_alpha (color) * fill_opacity + 0.5f)); - - ctx->paint_color (color); -} - - -/* - * Shape path emitter callback - */ - -static void -svg_shape_path_emit (hb_draw_funcs_t *dfuncs, void *draw_data, void *user_data) -{ - hb_svg_shape_emit_data_t *shape = (hb_svg_shape_emit_data_t *) user_data; - switch (shape->type) - { - case hb_svg_shape_emit_data_t::SHAPE_PATH: - svg_parse_path_data (shape->str_data, dfuncs, draw_data); - break; - case hb_svg_shape_emit_data_t::SHAPE_RECT: - svg_rect_to_path (shape->params[0], shape->params[1], - shape->params[2], shape->params[3], - shape->params[4], shape->params[5], - dfuncs, draw_data); - break; - case hb_svg_shape_emit_data_t::SHAPE_CIRCLE: - svg_circle_to_path (shape->params[0], shape->params[1], shape->params[2], - dfuncs, draw_data); - break; - case hb_svg_shape_emit_data_t::SHAPE_ELLIPSE: - svg_ellipse_to_path (shape->params[0], shape->params[1], - shape->params[2], shape->params[3], - dfuncs, draw_data); - break; - case hb_svg_shape_emit_data_t::SHAPE_LINE: - svg_line_to_path (shape->params[0], shape->params[1], - shape->params[2], shape->params[3], - dfuncs, draw_data); - break; - case hb_svg_shape_emit_data_t::SHAPE_POLYLINE: - svg_polygon_to_path (shape->str_data, false, dfuncs, draw_data); - break; - case hb_svg_shape_emit_data_t::SHAPE_POLYGON: - svg_polygon_to_path (shape->str_data, true, dfuncs, draw_data); - break; - } -} - -static bool -svg_parse_shape_tag (hb_svg_xml_parser_t &parser, - hb_svg_shape_emit_data_t *shape) -{ - hb_svg_str_t tag = parser.tag_name; - if (tag.eq ("path")) - { - hb_svg_str_t d = parser.find_attr ("d"); - if (!d.len) return false; - shape->type = hb_svg_shape_emit_data_t::SHAPE_PATH; - shape->str_data = d; - return true; - } - if (tag.eq ("rect")) - { - float w = svg_parse_float (parser.find_attr ("width")); - float h = svg_parse_float (parser.find_attr ("height")); - if (w <= 0 || h <= 0) return false; - shape->type = hb_svg_shape_emit_data_t::SHAPE_RECT; - shape->params[0] = svg_parse_float (parser.find_attr ("x")); - shape->params[1] = svg_parse_float (parser.find_attr ("y")); - shape->params[2] = w; - shape->params[3] = h; - shape->params[4] = svg_parse_float (parser.find_attr ("rx")); - shape->params[5] = svg_parse_float (parser.find_attr ("ry")); - return true; - } - if (tag.eq ("circle")) - { - float r = svg_parse_float (parser.find_attr ("r")); - if (r <= 0) return false; - shape->type = hb_svg_shape_emit_data_t::SHAPE_CIRCLE; - shape->params[0] = svg_parse_float (parser.find_attr ("cx")); - shape->params[1] = svg_parse_float (parser.find_attr ("cy")); - shape->params[2] = r; - return true; - } - if (tag.eq ("ellipse")) - { - float rx = svg_parse_float (parser.find_attr ("rx")); - float ry = svg_parse_float (parser.find_attr ("ry")); - if (rx <= 0 || ry <= 0) return false; - shape->type = hb_svg_shape_emit_data_t::SHAPE_ELLIPSE; - shape->params[0] = svg_parse_float (parser.find_attr ("cx")); - shape->params[1] = svg_parse_float (parser.find_attr ("cy")); - shape->params[2] = rx; - shape->params[3] = ry; - return true; - } - if (tag.eq ("line")) - { - shape->type = hb_svg_shape_emit_data_t::SHAPE_LINE; - shape->params[0] = svg_parse_float (parser.find_attr ("x1")); - shape->params[1] = svg_parse_float (parser.find_attr ("y1")); - shape->params[2] = svg_parse_float (parser.find_attr ("x2")); - shape->params[3] = svg_parse_float (parser.find_attr ("y2")); - return true; - } - if (tag.eq ("polyline")) - { - hb_svg_str_t points = parser.find_attr ("points"); - if (!points.len) return false; - shape->type = hb_svg_shape_emit_data_t::SHAPE_POLYLINE; - shape->str_data = points; - return true; - } - if (tag.eq ("polygon")) - { - hb_svg_str_t points = parser.find_attr ("points"); - if (!points.len) return false; - shape->type = hb_svg_shape_emit_data_t::SHAPE_POLYGON; - shape->str_data = points; - return true; - } - return false; -} - - - -/* - * 11. Element renderer — recursive SVG rendering - */ - -static void svg_render_element (hb_svg_render_context_t *ctx, - hb_svg_xml_parser_t &parser, - hb_svg_str_t inherited_fill, - float inherited_fill_opacity, - hb_svg_str_t inherited_clip_path); - -/* Parse a gradient element */ -static bool -svg_parse_gradient_stop (hb_svg_xml_parser_t &parser, - hb_svg_gradient_t &grad, - hb_paint_funcs_t *pfuncs, - void *paint_data, - hb_color_t foreground, - hb_face_t *face, - unsigned palette) -{ - hb_svg_str_t offset_str = parser.find_attr ("offset"); - hb_svg_str_t color_str = parser.find_attr ("stop-color"); - hb_svg_str_t opacity_str = parser.find_attr ("stop-opacity"); - - float offset = 0; - if (offset_str.len) - { - offset = svg_parse_float (offset_str); - /* Check for percentage */ - if (offset_str.len && offset_str.data[offset_str.len - 1] == '%') - offset /= 100.f; - } - - bool is_none = false; - hb_color_t color = HB_COLOR (0, 0, 0, 255); - if (color_str.len) - color = svg_parse_color (color_str, pfuncs, paint_data, foreground, face, palette, &is_none); - - if (opacity_str.len) - { - float opacity = svg_parse_float (opacity_str); - color = HB_COLOR (hb_color_get_blue (color), - hb_color_get_green (color), - hb_color_get_red (color), - (uint8_t) (hb_color_get_alpha (color) * opacity + 0.5f)); - } - - hb_svg_gradient_stop_t stop = {offset, color}; - grad.stops.push (stop); - return !grad.stops.in_error (); -} - -static hb_svg_str_t -svg_find_href_attr (const hb_svg_xml_parser_t &parser) -{ - hb_svg_str_t href = parser.find_attr ("href"); - if (href.is_null ()) - href = parser.find_attr ("xlink:href"); - return href; -} - -/* Parse gradient element attributes */ -static void -svg_parse_gradient_attrs (hb_svg_xml_parser_t &parser, - hb_svg_gradient_t &grad) -{ - hb_svg_str_t spread_str = parser.find_attr ("spreadMethod"); - if (spread_str.eq ("reflect")) - { - grad.spread = HB_PAINT_EXTEND_REFLECT; - grad.has_spread = true; - } - else if (spread_str.eq ("repeat")) - { - grad.spread = HB_PAINT_EXTEND_REPEAT; - grad.has_spread = true; - } - else if (spread_str.eq ("pad")) - { - grad.spread = HB_PAINT_EXTEND_PAD; - grad.has_spread = true; - } - - hb_svg_str_t units_str = parser.find_attr ("gradientUnits"); - if (units_str.eq ("userSpaceOnUse")) - { - grad.units_user_space = true; - grad.has_units_user_space = true; - } - else if (units_str.eq ("objectBoundingBox")) - { - grad.units_user_space = false; - grad.has_units_user_space = true; - } - - hb_svg_str_t transform_str = parser.find_attr ("gradientTransform"); - if (transform_str.len) - { - grad.has_gradient_transform = true; - svg_parse_transform (transform_str, &grad.gradient_transform); - } - - hb_svg_str_t href = svg_find_href_attr (parser); - if (href.len && href.data[0] == '#') - { - unsigned n = hb_min (href.len - 1, (unsigned) sizeof (grad.href_id) - 1); - memcpy (grad.href_id, href.data + 1, n); - grad.href_id[n] = '\0'; - } -} - -static void -svg_parse_gradient_geometry_attrs (hb_svg_xml_parser_t &parser, - hb_svg_gradient_t &grad) -{ - if (grad.type == SVG_GRADIENT_LINEAR) - { - hb_svg_str_t x1_str = parser.find_attr ("x1"); - hb_svg_str_t y1_str = parser.find_attr ("y1"); - hb_svg_str_t x2_str = parser.find_attr ("x2"); - hb_svg_str_t y2_str = parser.find_attr ("y2"); - if (x1_str.len) { grad.x1 = svg_parse_float (x1_str); grad.has_x1 = true; } - if (y1_str.len) { grad.y1 = svg_parse_float (y1_str); grad.has_y1 = true; } - if (x2_str.len) { grad.x2 = svg_parse_float (x2_str); grad.has_x2 = true; } - if (y2_str.len) { grad.y2 = svg_parse_float (y2_str); grad.has_y2 = true; } - - /* Default x2 to 1 if not explicitly set (objectBoundingBox default). */ - if (!grad.has_x2) - grad.x2 = 1.f; - } - else /* SVG_GRADIENT_RADIAL */ - { - hb_svg_str_t cx_str = parser.find_attr ("cx"); - hb_svg_str_t cy_str = parser.find_attr ("cy"); - hb_svg_str_t r_str = parser.find_attr ("r"); - hb_svg_str_t fx_str = parser.find_attr ("fx"); - hb_svg_str_t fy_str = parser.find_attr ("fy"); - - if (cx_str.len) { grad.cx = svg_parse_float (cx_str); grad.has_cx = true; } - if (cy_str.len) { grad.cy = svg_parse_float (cy_str); grad.has_cy = true; } - if (r_str.len) { grad.r = svg_parse_float (r_str); grad.has_r = true; } - if (fx_str.len) { grad.fx = svg_parse_float (fx_str); grad.has_fx = true; } - if (fy_str.len) { grad.fy = svg_parse_float (fy_str); grad.has_fy = true; } - } -} - -static void -svg_parse_gradient_children (hb_svg_render_context_t *ctx, - hb_svg_xml_parser_t &parser, - hb_svg_gradient_t &grad, - hb_svg_str_t *id) -{ - int gdepth = 1; - bool had_alloc_failure = false; - while (gdepth > 0) - { - hb_svg_token_type_t gt = parser.next (); - if (gt == SVG_TOKEN_EOF) break; - if (gt == SVG_TOKEN_CLOSE_TAG) { gdepth--; continue; } - if ((gt == SVG_TOKEN_OPEN_TAG || gt == SVG_TOKEN_SELF_CLOSE_TAG) && - parser.tag_name.eq ("stop")) - if (unlikely (!svg_parse_gradient_stop (parser, grad, - ctx->pfuncs, ctx->paint, - ctx->foreground, hb_font_get_face (ctx->font), - ctx->palette))) - had_alloc_failure = true; - if (gt == SVG_TOKEN_OPEN_TAG && !parser.tag_name.eq ("stop")) - gdepth++; - } - if (had_alloc_failure) - *id = {}; -} - -static void -svg_process_gradient_def (hb_svg_render_context_t *ctx, - hb_svg_xml_parser_t &parser, - hb_svg_token_type_t tok, - hb_svg_gradient_type_t type) -{ - hb_svg_gradient_t grad; - grad.type = type; - /* Parse geometry and common gradient attrs from the opening tag. */ - svg_parse_gradient_geometry_attrs (parser, grad); - svg_parse_gradient_attrs (parser, grad); - - hb_svg_str_t id = parser.find_attr ("id"); - /* Child elements are only present for non-self-closing gradients. */ - if (tok == SVG_TOKEN_OPEN_TAG) - svg_parse_gradient_children (ctx, parser, grad, &id); - - if (id.len) - { - char id_buf[64]; - unsigned n = hb_min (id.len, (unsigned) sizeof (id_buf) - 1); - memcpy (id_buf, id.data, n); - id_buf[n] = '\0'; - (void) ctx->defs.add_gradient (id_buf, grad); - } -} - -static void -svg_process_clip_path_def (hb_svg_render_context_t *ctx, - hb_svg_xml_parser_t &parser, - hb_svg_token_type_t tok) -{ - hb_svg_clip_path_def_t clip; - hb_svg_str_t id = parser.find_attr ("id"); - hb_svg_str_t units = parser.find_attr ("clipPathUnits"); - if (units.eq ("objectBoundingBox")) - clip.units_user_space = false; - else - clip.units_user_space = true; - - hb_svg_str_t cp_transform = parser.find_attr ("transform"); - if (cp_transform.len) - { - clip.has_clip_transform = true; - svg_parse_transform (cp_transform, &clip.clip_transform); - } - - clip.first_shape = ctx->defs.clip_shapes.length; - clip.shape_count = 0; - - /* Collect top-level geometry children of . */ - if (tok == SVG_TOKEN_OPEN_TAG) - { - int cdepth = 1; - bool had_alloc_failure = false; - while (cdepth > 0) - { - hb_svg_token_type_t ct = parser.next (); - if (ct == SVG_TOKEN_EOF) break; - if (ct == SVG_TOKEN_CLOSE_TAG) { cdepth--; continue; } - if (ct == SVG_TOKEN_OPEN_TAG || ct == SVG_TOKEN_SELF_CLOSE_TAG) - { - if (cdepth == 1) - { - hb_svg_shape_emit_data_t shape; - if (svg_parse_shape_tag (parser, &shape)) - { - hb_svg_clip_shape_t clip_shape; - clip_shape.shape = shape; - hb_svg_str_t sh_transform = parser.find_attr ("transform"); - if (sh_transform.len) - { - clip_shape.has_transform = true; - svg_parse_transform (sh_transform, &clip_shape.transform); - } - ctx->defs.clip_shapes.push (clip_shape); - if (likely (!ctx->defs.clip_shapes.in_error ())) - clip.shape_count++; - else - had_alloc_failure = true; - } - } - if (ct == SVG_TOKEN_OPEN_TAG) - cdepth++; - } - } - if (had_alloc_failure) - id = {}; - } - - if (id.len && clip.shape_count) - { - char id_buf[64]; - unsigned n = hb_min (id.len, (unsigned) sizeof (id_buf) - 1); - memcpy (id_buf, id.data, n); - id_buf[n] = '\0'; - (void) ctx->defs.add_clip_path (id_buf, clip); - } -} - -/* Process children — gradients, clipPaths */ -static void -svg_process_defs (hb_svg_render_context_t *ctx, hb_svg_xml_parser_t &parser) -{ - int depth = 1; - - while (depth > 0) - { - hb_svg_token_type_t tok = parser.next (); - if (tok == SVG_TOKEN_EOF) break; - - if (tok == SVG_TOKEN_CLOSE_TAG) - { - depth--; - continue; - } - - if (tok == SVG_TOKEN_OPEN_TAG || tok == SVG_TOKEN_SELF_CLOSE_TAG) - { - /* Dispatch supported defs entries to focused helpers. */ - if (parser.tag_name.eq ("linearGradient")) - svg_process_gradient_def (ctx, parser, tok, SVG_GRADIENT_LINEAR); - else if (parser.tag_name.eq ("radialGradient")) - svg_process_gradient_def (ctx, parser, tok, SVG_GRADIENT_RADIAL); - else if (parser.tag_name.eq ("clipPath")) - svg_process_clip_path_def (ctx, parser, tok); - else - { - /* Skip unknown defs children */ - if (tok == SVG_TOKEN_OPEN_TAG) - depth++; - } - } - } -} - -static bool -svg_find_element_by_id (const hb_svg_render_context_t *ctx, - const char *id, - const char **found) -{ - *found = nullptr; - if (ctx->doc_cache) - { - unsigned start = 0, end = 0; - if (ctx->svg_accel->doc_cache_find_id_cstr (ctx->doc_cache, id, &start, &end)) - { - if (start < ctx->doc_len && end <= ctx->doc_len && start < end) - { - *found = ctx->doc_start + start; - return true; - } - } - } - - hb_svg_xml_parser_t search (ctx->doc_start, ctx->doc_len); - while (true) - { - hb_svg_token_type_t tok = search.next (); - if (tok == SVG_TOKEN_EOF) break; - if (tok != SVG_TOKEN_OPEN_TAG && tok != SVG_TOKEN_SELF_CLOSE_TAG) continue; - hb_svg_str_t attr_id = search.find_attr ("id"); - if (attr_id.len && attr_id.eq_cstr (id)) - { - *found = search.tag_start; - return true; - } - } - return false; -} - -struct hb_svg_clip_emit_data_t -{ - const hb_svg_defs_t *defs; - const hb_svg_clip_path_def_t *clip; - hb_transform_t<> base_transform; - hb_transform_t<> bbox_transform; - bool has_bbox_transform = false; -}; - -static inline hb_transform_t<> -svg_to_hb_transform (const hb_svg_transform_t &t) -{ - return hb_transform_t<> (t.xx, t.yx, t.xy, t.yy, t.dx, t.dy); -} - -static void -svg_clip_path_emit (hb_draw_funcs_t *dfuncs, - void *draw_data, - void *user_data) -{ - hb_raster_draw_t *rdr = (hb_raster_draw_t *) draw_data; - hb_svg_clip_emit_data_t *ed = (hb_svg_clip_emit_data_t *) user_data; - const hb_svg_clip_path_def_t *clip = ed->clip; - - for (unsigned i = 0; i < clip->shape_count; i++) - { - const hb_svg_clip_shape_t &s = ed->defs->clip_shapes[clip->first_shape + i]; - hb_transform_t<> t = ed->base_transform; - if (ed->has_bbox_transform) - t.multiply (ed->bbox_transform); - if (clip->has_clip_transform) - t.multiply (svg_to_hb_transform (clip->clip_transform)); - if (s.has_transform) - t.multiply (svg_to_hb_transform (s.transform)); - - hb_raster_draw_set_transform (rdr, t.xx, t.yx, t.xy, t.yy, t.x0, t.y0); - - hb_svg_shape_emit_data_t shape = s.shape; - svg_shape_path_emit (dfuncs, draw_data, &shape); - } -} - -static bool -svg_push_clip_path_ref (hb_svg_render_context_t *ctx, - hb_svg_str_t clip_path_str, - const hb_extents_t<> *object_bbox) -{ - if (clip_path_str.is_null ()) return false; - hb_svg_str_t trimmed = clip_path_str.trim (); - if (!trimmed.len || trimmed.eq ("none")) return false; - - const hb_svg_clip_path_def_t *clip = ctx->defs.find_clip_path_str (trimmed); - if (!clip || !clip->shape_count) return false; - - hb_svg_clip_emit_data_t ed; - ed.defs = &ctx->defs; - ed.clip = clip; - ed.base_transform = ctx->paint->current_effective_transform (); - - if (!clip->units_user_space) - { - if (!object_bbox || object_bbox->is_empty ()) - return false; - float w = object_bbox->xmax - object_bbox->xmin; - float h = object_bbox->ymax - object_bbox->ymin; - if (w <= 0 || h <= 0) - return false; - ed.has_bbox_transform = true; - ed.bbox_transform = hb_transform_t<> (w, 0, 0, h, object_bbox->xmin, object_bbox->ymin); - } - - hb_raster_paint_push_clip_path (ctx->paint, svg_clip_path_emit, &ed); - return true; -} - -static void -svg_bbox_move_to (hb_draw_funcs_t *dfuncs HB_UNUSED, - void *draw_data, - hb_draw_state_t *st HB_UNUSED, - float to_x, float to_y, - void *user_data HB_UNUSED) -{ - ((hb_extents_t<> *) draw_data)->add_point (to_x, to_y); -} - -static void -svg_bbox_line_to (hb_draw_funcs_t *dfuncs HB_UNUSED, - void *draw_data, - hb_draw_state_t *st HB_UNUSED, - float to_x, float to_y, - void *user_data HB_UNUSED) -{ - ((hb_extents_t<> *) draw_data)->add_point (to_x, to_y); -} - -static void -svg_bbox_quadratic_to (hb_draw_funcs_t *dfuncs HB_UNUSED, - void *draw_data, - hb_draw_state_t *st HB_UNUSED, - float control_x, float control_y, - float to_x, float to_y, - void *user_data HB_UNUSED) -{ - hb_extents_t<> *ext = (hb_extents_t<> *) draw_data; - ext->add_point (control_x, control_y); - ext->add_point (to_x, to_y); -} - -static void -svg_bbox_cubic_to (hb_draw_funcs_t *dfuncs HB_UNUSED, - void *draw_data, - hb_draw_state_t *st HB_UNUSED, - float control1_x, float control1_y, - float control2_x, float control2_y, - float to_x, float to_y, - void *user_data HB_UNUSED) -{ - hb_extents_t<> *ext = (hb_extents_t<> *) draw_data; - ext->add_point (control1_x, control1_y); - ext->add_point (control2_x, control2_y); - ext->add_point (to_x, to_y); -} - -static hb_draw_funcs_t * -svg_bbox_draw_funcs () -{ - static hb_draw_funcs_t *funcs = nullptr; - if (unlikely (!funcs)) - { - funcs = hb_draw_funcs_create (); - hb_draw_funcs_set_move_to_func (funcs, svg_bbox_move_to, nullptr, nullptr); - hb_draw_funcs_set_line_to_func (funcs, svg_bbox_line_to, nullptr, nullptr); - hb_draw_funcs_set_quadratic_to_func (funcs, svg_bbox_quadratic_to, nullptr, nullptr); - hb_draw_funcs_set_cubic_to_func (funcs, svg_bbox_cubic_to, nullptr, nullptr); - hb_draw_funcs_make_immutable (funcs); - } - return funcs; -} - -static bool -svg_compute_shape_bbox (const hb_svg_shape_emit_data_t &shape, - hb_extents_t<> *bbox) -{ - hb_extents_t<> ext; - hb_svg_shape_emit_data_t tmp = shape; - svg_shape_path_emit (svg_bbox_draw_funcs (), &ext, &tmp); - if (ext.is_empty ()) return false; - *bbox = ext; - return true; -} - - -/* Render a single shape element */ -static void -svg_render_shape (hb_svg_render_context_t *ctx, - hb_svg_shape_emit_data_t &shape, - hb_svg_str_t fill_str, - float fill_opacity, - float opacity, - hb_svg_str_t transform_str, - hb_svg_str_t clip_path_str) -{ - bool has_transform = transform_str.len > 0; - bool has_opacity = opacity < 1.f; - bool has_clip_path = false; - - if (has_opacity) - ctx->push_group (); - - if (has_transform) - { - hb_svg_transform_t t; - svg_parse_transform (transform_str, &t); - ctx->push_transform (t.xx, t.yx, t.xy, t.yy, t.dx, t.dy); - } - - hb_extents_t<> bbox; - bool has_bbox = svg_compute_shape_bbox (shape, &bbox); - has_clip_path = svg_push_clip_path_ref (ctx, clip_path_str, has_bbox ? &bbox : nullptr); - - /* Clip with shape path, then fill */ - hb_raster_paint_push_clip_path (ctx->paint, svg_shape_path_emit, &shape); - - /* Default fill is black */ - if (fill_str.is_null ()) - { - hb_color_t black = HB_COLOR (0, 0, 0, 255); - if (fill_opacity < 1.f) - black = HB_COLOR (0, 0, 0, (uint8_t) (255 * fill_opacity + 0.5f)); - ctx->paint_color (black); - } - else - svg_emit_fill (ctx, fill_str, fill_opacity, has_bbox ? &bbox : nullptr); - - ctx->pop_clip (); - if (has_clip_path) - ctx->pop_clip (); - - if (has_transform) - ctx->pop_transform (); - - if (has_opacity) - ctx->pop_group (HB_PAINT_COMPOSITE_MODE_SRC_OVER); -} - -static void -svg_render_container_element (hb_svg_render_context_t *ctx, - hb_svg_xml_parser_t &parser, - hb_svg_str_t tag, - bool self_closing, - hb_svg_str_t fill_str, - float fill_opacity, - float opacity, - hb_svg_str_t transform_str, - hb_svg_str_t clip_path_str) -{ - bool has_transform = transform_str.len > 0; - bool has_opacity = opacity < 1.f; - bool has_clip = false; - bool has_viewbox = false; - float vb_x = 0, vb_y = 0, vb_w = 0, vb_h = 0; - - if (tag.eq ("svg")) - { - hb_svg_str_t viewbox_str = parser.find_attr ("viewBox"); - if (viewbox_str.len) - { - has_viewbox = true; - hb_svg_float_parser_t vb_fp (viewbox_str); - vb_x = vb_fp.next_float (); - vb_y = vb_fp.next_float (); - vb_w = vb_fp.next_float (); - vb_h = vb_fp.next_float (); - } - } - - if (has_opacity) - ctx->push_group (); - - if (has_transform) - { - hb_svg_transform_t t; - svg_parse_transform (transform_str, &t); - ctx->push_transform (t.xx, t.yx, t.xy, t.yy, t.dx, t.dy); - } - - if (has_viewbox && vb_w > 0 && vb_h > 0) - ctx->push_transform (1, 0, 0, 1, -vb_x, -vb_y); - - has_clip = svg_push_clip_path_ref (ctx, clip_path_str, nullptr); - - if (!self_closing) - { - int depth = 1; - while (depth > 0) - { - hb_svg_token_type_t tok = parser.next (); - if (tok == SVG_TOKEN_EOF) break; - - if (tok == SVG_TOKEN_CLOSE_TAG) - { - depth--; - continue; - } - - if (tok == SVG_TOKEN_OPEN_TAG || tok == SVG_TOKEN_SELF_CLOSE_TAG) - { - hb_svg_str_t child_tag = parser.tag_name; - if (parser.tag_name.eq ("defs")) - { - if (tok != SVG_TOKEN_SELF_CLOSE_TAG) - svg_process_defs (ctx, parser); - continue; - } - svg_render_element (ctx, parser, fill_str, fill_opacity, clip_path_str); - if (tok == SVG_TOKEN_OPEN_TAG && !child_tag.eq ("g") && - !child_tag.eq ("svg") && !child_tag.eq ("use")) - { - /* Skip children of non-container elements we don't handle. */ - int skip_depth = 1; - while (skip_depth > 0) - { - hb_svg_token_type_t st = parser.next (); - if (st == SVG_TOKEN_EOF) break; - if (st == SVG_TOKEN_CLOSE_TAG) skip_depth--; - else if (st == SVG_TOKEN_OPEN_TAG) skip_depth++; - } - } - } - } - } - - if (has_viewbox && vb_w > 0 && vb_h > 0) - ctx->pop_transform (); - - if (has_clip) - ctx->pop_clip (); - - if (has_transform) - ctx->pop_transform (); - - if (has_opacity) - ctx->pop_group (HB_PAINT_COMPOSITE_MODE_SRC_OVER); -} - -static bool -svg_render_primitive_shape_element (hb_svg_render_context_t *ctx, - hb_svg_xml_parser_t &parser, - hb_svg_str_t tag, - hb_svg_str_t fill_str, - float fill_opacity, - float opacity, - hb_svg_str_t transform_str, - hb_svg_str_t clip_path_str) -{ - if (tag.eq ("path")) - { - hb_svg_str_t d = parser.find_attr ("d"); - if (d.len) - { - hb_svg_shape_emit_data_t shape; - shape.type = hb_svg_shape_emit_data_t::SHAPE_PATH; - shape.str_data = d; - svg_render_shape (ctx, shape, fill_str, fill_opacity, opacity, transform_str, clip_path_str); - } - return true; - } - if (tag.eq ("rect")) - { - float x = svg_parse_float (parser.find_attr ("x")); - float y = svg_parse_float (parser.find_attr ("y")); - float w = svg_parse_float (parser.find_attr ("width")); - float h = svg_parse_float (parser.find_attr ("height")); - float rx = svg_parse_float (parser.find_attr ("rx")); - float ry = svg_parse_float (parser.find_attr ("ry")); - - if (w > 0 && h > 0) - { - hb_svg_shape_emit_data_t shape; - shape.type = hb_svg_shape_emit_data_t::SHAPE_RECT; - shape.params[0] = x; - shape.params[1] = y; - shape.params[2] = w; - shape.params[3] = h; - shape.params[4] = rx; - shape.params[5] = ry; - svg_render_shape (ctx, shape, fill_str, fill_opacity, opacity, transform_str, clip_path_str); - } - return true; - } - if (tag.eq ("circle")) - { - float cx = svg_parse_float (parser.find_attr ("cx")); - float cy = svg_parse_float (parser.find_attr ("cy")); - float r = svg_parse_float (parser.find_attr ("r")); - - if (r > 0) - { - hb_svg_shape_emit_data_t shape; - shape.type = hb_svg_shape_emit_data_t::SHAPE_CIRCLE; - shape.params[0] = cx; - shape.params[1] = cy; - shape.params[2] = r; - svg_render_shape (ctx, shape, fill_str, fill_opacity, opacity, transform_str, clip_path_str); - } - return true; - } - if (tag.eq ("ellipse")) - { - float cx = svg_parse_float (parser.find_attr ("cx")); - float cy = svg_parse_float (parser.find_attr ("cy")); - float rx = svg_parse_float (parser.find_attr ("rx")); - float ry = svg_parse_float (parser.find_attr ("ry")); - - if (rx > 0 && ry > 0) - { - hb_svg_shape_emit_data_t shape; - shape.type = hb_svg_shape_emit_data_t::SHAPE_ELLIPSE; - shape.params[0] = cx; - shape.params[1] = cy; - shape.params[2] = rx; - shape.params[3] = ry; - svg_render_shape (ctx, shape, fill_str, fill_opacity, opacity, transform_str, clip_path_str); - } - return true; - } - if (tag.eq ("line")) - { - float x1 = svg_parse_float (parser.find_attr ("x1")); - float y1 = svg_parse_float (parser.find_attr ("y1")); - float x2 = svg_parse_float (parser.find_attr ("x2")); - float y2 = svg_parse_float (parser.find_attr ("y2")); - - hb_svg_shape_emit_data_t shape; - shape.type = hb_svg_shape_emit_data_t::SHAPE_LINE; - shape.params[0] = x1; - shape.params[1] = y1; - shape.params[2] = x2; - shape.params[3] = y2; - svg_render_shape (ctx, shape, fill_str, fill_opacity, opacity, transform_str, clip_path_str); - return true; - } - if (tag.eq ("polyline")) - { - hb_svg_str_t points = parser.find_attr ("points"); - if (points.len) - { - hb_svg_shape_emit_data_t shape; - shape.type = hb_svg_shape_emit_data_t::SHAPE_POLYLINE; - shape.str_data = points; - svg_render_shape (ctx, shape, fill_str, fill_opacity, opacity, transform_str, clip_path_str); - } - return true; - } - if (tag.eq ("polygon")) - { - hb_svg_str_t points = parser.find_attr ("points"); - if (points.len) - { - hb_svg_shape_emit_data_t shape; - shape.type = hb_svg_shape_emit_data_t::SHAPE_POLYGON; - shape.str_data = points; - svg_render_shape (ctx, shape, fill_str, fill_opacity, opacity, transform_str, clip_path_str); - } - return true; - } - - return false; -} - -static void -svg_render_use_element (hb_svg_render_context_t *ctx, - hb_svg_xml_parser_t &parser, - hb_svg_str_t fill_str, - float fill_opacity, - hb_svg_str_t transform_str, - hb_svg_str_t clip_path_str) -{ - hb_svg_str_t href = svg_find_href_attr (parser); - - char ref_id[64]; - if (!hb_svg_defs_t::parse_fragment_id (href, ref_id)) - return; - - float use_x = svg_parse_float (parser.find_attr ("x")); - float use_y = svg_parse_float (parser.find_attr ("y")); - - bool has_translate = (use_x != 0.f || use_y != 0.f); - bool has_use_transform = transform_str.len > 0; - - if (has_use_transform) - { - hb_svg_transform_t t; - svg_parse_transform (transform_str, &t); - ctx->push_transform (t.xx, t.yx, t.xy, t.yy, t.dx, t.dy); - } - - if (has_translate) - ctx->push_transform (1, 0, 0, 1, use_x, use_y); - - const char *found = nullptr; - svg_find_element_by_id (ctx, ref_id, &found); - - if (found) - { - unsigned remaining = ctx->doc_start + ctx->doc_len - found; - hb_svg_xml_parser_t ref_parser (found, remaining); - hb_svg_token_type_t tok = ref_parser.next (); - if (tok == SVG_TOKEN_OPEN_TAG || tok == SVG_TOKEN_SELF_CLOSE_TAG) - svg_render_element (ctx, ref_parser, fill_str, fill_opacity, clip_path_str); - } - - if (has_translate) - ctx->pop_transform (); - - if (has_use_transform) - ctx->pop_transform (); -} - -/* Render one element (may be a container or shape) */ -static void -svg_render_element (hb_svg_render_context_t *ctx, - hb_svg_xml_parser_t &parser, - hb_svg_str_t inherited_fill, - float inherited_fill_opacity, - hb_svg_str_t inherited_clip_path) -{ - if (ctx->depth >= SVG_MAX_DEPTH) return; - - const HB_UNUSED unsigned transform_depth = ctx->paint->transform_stack.length; - const HB_UNUSED unsigned clip_depth = ctx->paint->clip_stack.length; - const HB_UNUSED unsigned surface_depth = ctx->paint->surface_stack.length; - - ctx->depth++; - - hb_svg_str_t tag = parser.tag_name; - bool self_closing = parser.self_closing; - - /* Extract common attributes */ - hb_svg_str_t fill_attr = parser.find_attr ("fill"); - hb_svg_str_t fill_opacity_str = parser.find_attr ("fill-opacity"); - hb_svg_str_t opacity_str = parser.find_attr ("opacity"); - hb_svg_str_t transform_str = parser.find_attr ("transform"); - hb_svg_str_t clip_path_attr = parser.find_attr ("clip-path"); - - hb_svg_str_t fill_str = fill_attr.is_null () ? inherited_fill : fill_attr; - float fill_opacity = fill_opacity_str.len ? svg_parse_float (fill_opacity_str) : inherited_fill_opacity; - float opacity = opacity_str.len ? svg_parse_float (opacity_str) : 1.f; - hb_svg_str_t clip_path_str = clip_path_attr.is_null () ? inherited_clip_path : clip_path_attr; - - if (tag.eq ("g") || tag.eq ("svg")) - svg_render_container_element (ctx, parser, tag, self_closing, - fill_str, fill_opacity, opacity, - transform_str, clip_path_str); - else if (svg_render_primitive_shape_element (ctx, parser, tag, - fill_str, fill_opacity, opacity, - transform_str, clip_path_str)) - ; - else if (tag.eq ("use")) - svg_render_use_element (ctx, parser, fill_str, fill_opacity, - transform_str, clip_path_str); - - ctx->depth--; - - assert (ctx->paint->transform_stack.length == transform_depth); - assert (ctx->paint->clip_stack.length == clip_depth); - assert (ctx->paint->surface_stack.length == surface_depth); -} - - -/* - * 12. Entry point - */ - -hb_bool_t -hb_raster_svg_render (hb_raster_paint_t *paint, - hb_blob_t *blob, - hb_codepoint_t glyph, - hb_font_t *font, - unsigned palette, - hb_color_t foreground) -{ - unsigned data_len; - const char *data = hb_blob_get_data (blob, &data_len); - if (!data || !data_len) return false; - - hb_face_t *face = hb_font_get_face (font); - const OT::SVG::svg_doc_cache_t *doc_cache = nullptr; - unsigned doc_index = 0; - hb_codepoint_t start_glyph = HB_CODEPOINT_INVALID; - hb_codepoint_t end_glyph = HB_CODEPOINT_INVALID; - - if (face && - hb_ot_color_glyph_get_svg_document_index (face, glyph, &doc_index) && - hb_ot_color_get_svg_document_glyph_range (face, doc_index, &start_glyph, &end_glyph)) - doc_cache = face->table.SVG->get_or_create_doc_cache (blob, data, data_len, - doc_index, start_glyph, end_glyph); - - if (doc_cache) - data = face->table.SVG->doc_cache_get_svg (doc_cache, &data_len); - - hb_paint_funcs_t *pfuncs = hb_raster_paint_get_funcs (); - - hb_svg_render_context_t ctx; - ctx.paint = paint; - ctx.pfuncs = pfuncs; - ctx.font = font; - ctx.palette = palette; - ctx.foreground = foreground; - ctx.doc_start = data; - ctx.doc_len = data_len; - ctx.svg_accel = face ? face->table.SVG.get () : nullptr; - ctx.doc_cache = doc_cache; - - /* First pass: collect defs (gradients, clip-paths) from the entire document */ - { - hb_svg_xml_parser_t defs_parser (data, data_len); - while (true) - { - hb_svg_token_type_t tok = defs_parser.next (); - if (tok == SVG_TOKEN_EOF) break; - if ((tok == SVG_TOKEN_OPEN_TAG) && defs_parser.tag_name.eq ("defs")) - svg_process_defs (&ctx, defs_parser); - } - } - - bool found_glyph = false; - unsigned glyph_start = 0, glyph_end = 0; - if (doc_cache && face->table.SVG->doc_cache_get_glyph_span (doc_cache, glyph, &glyph_start, &glyph_end)) - { - hb_svg_xml_parser_t parser (data + glyph_start, glyph_end - glyph_start); - hb_svg_token_type_t tok = parser.next (); - if (tok == SVG_TOKEN_OPEN_TAG || tok == SVG_TOKEN_SELF_CLOSE_TAG) - { - hb_paint_push_font_transform (ctx.pfuncs, ctx.paint, font); - ctx.push_transform (1, 0, 0, -1, 0, 0); - svg_render_element (&ctx, parser, hb_svg_str_t (), 1.f, hb_svg_str_t ()); - ctx.pop_transform (); - hb_paint_pop_transform (ctx.pfuncs, ctx.paint); - found_glyph = true; - } - } - else - { - /* Fallback for malformed/uncached docs: linear scan by glyph id. */ - char glyph_id_str[32]; - snprintf (glyph_id_str, sizeof (glyph_id_str), "glyph%u", glyph); - hb_svg_xml_parser_t parser (data, data_len); - while (true) - { - hb_svg_token_type_t tok = parser.next (); - if (tok == SVG_TOKEN_EOF) break; - - if (tok == SVG_TOKEN_OPEN_TAG || tok == SVG_TOKEN_SELF_CLOSE_TAG) - { - hb_svg_str_t id = parser.find_attr ("id"); - if (id.len) - { - char id_buf[64]; - unsigned n = hb_min (id.len, (unsigned) sizeof (id_buf) - 1); - memcpy (id_buf, id.data, n); - id_buf[n] = '\0'; - - if (strcmp (id_buf, glyph_id_str) == 0) - { - hb_paint_push_font_transform (ctx.pfuncs, ctx.paint, font); - ctx.push_transform (1, 0, 0, -1, 0, 0); - svg_render_element (&ctx, parser, hb_svg_str_t (), 1.f, hb_svg_str_t ()); - ctx.pop_transform (); - hb_paint_pop_transform (ctx.pfuncs, ctx.paint); - found_glyph = true; - break; - } - } - } - } - } - - return found_glyph; -} diff --git a/src/meson.build b/src/meson.build index c9a2f6f6b..e07dcc1c6 100644 --- a/src/meson.build +++ b/src/meson.build @@ -705,9 +705,30 @@ hb_raster_sources = [ 'hb-raster-image.hh', 'hb-raster-utils.hh', 'hb-raster-draw.cc', + 'hb-raster-svg-base.cc', + 'hb-raster-svg-base.hh', + 'hb-raster-svg-defs.cc', + 'hb-raster-svg-defs.hh', + 'hb-raster-svg-defs-scan.cc', + 'hb-raster-svg-defs-scan.hh', + 'hb-raster-svg-gradient.cc', + 'hb-raster-svg-gradient.hh', + 'hb-raster-svg-clip.cc', + 'hb-raster-svg-clip.hh', + 'hb-raster-svg-bbox.cc', + 'hb-raster-svg-bbox.hh', + 'hb-raster-svg-fill.cc', + 'hb-raster-svg-fill.hh', + 'hb-raster-svg-context.hh', + 'hb-raster-svg-use.cc', + 'hb-raster-svg-use.hh', + 'hb-raster-svg-render.cc', + 'hb-raster-svg-color.cc', + 'hb-raster-svg-color.hh', + 'hb-raster-svg-parse.cc', + 'hb-raster-svg-parse.hh', 'hb-raster-paint.cc', 'hb-raster-paint.hh', - 'hb-raster-svg.cc', 'hb-raster-svg.hh', 'hb-static.cc', ]