Godot Engine – Multi-platform 2D and 3D game engine
harfbuzz: Update to 14.4.0
Jakub Marcowski971f96a83396
diff --git a/modules/text_server_adv/SCsub b/modules/text_server_adv/SCsubindex 1eb77fcd7de..5ea5e823e8e 100644--- a/modules/text_server_adv/SCsub+++ b/modules/text_server_adv/SCsub@@ -45,6 +45,7 @@ if env["builtin_harfbuzz"]:"src/hb-common.cc",# "src/hb-coretext-font.cc",# "src/hb-coretext-shape.cc",+ # "src/hb-depend.cc",# "src/hb-directwrite.cc","src/hb-draw.cc","src/hb-face-builder.cc",@@ -62,6 +63,7 @@ if env["builtin_harfbuzz"]:"src/hb-ot-cff2-table.cc","src/hb-ot-color.cc","src/hb-ot-face.cc",+ # "src/hb-ot-fetch.cc","src/hb-ot-font.cc","src/hb-ot-layout.cc","src/hb-ot-map.cc",diff --git a/thirdparty/README.md b/thirdparty/README.mdindex fbc5cd4fb7a..148584c4728 100644--- a/thirdparty/README.md+++ b/thirdparty/README.md@@ -469,7 +469,7 @@ Patches:## harfbuzz- Upstream: https://github.com/harfbuzz/harfbuzz-- Version: 14.2.0 (b0ffab42d473eb380ad0fcf42730e0f1868cbc97, 2026)+- Version: 14.4.0 (36cb489cb02ce4b92099669ba9f9bea348eff93f, 2026)- License: MITFiles extracted from upstream source:diff --git a/thirdparty/harfbuzz/src/OT/Color/CBDT/CBDT.hh b/thirdparty/harfbuzz/src/OT/Color/CBDT/CBDT.hhindex 2d8f1da52dd..f11dab7bcbb 100644--- a/thirdparty/harfbuzz/src/OT/Color/CBDT/CBDT.hh+++ b/thirdparty/harfbuzz/src/OT/Color/CBDT/CBDT.hh@@ -207,8 +207,8 @@ struct IndexSubtablehb_barrier ();switch (u.header.indexFormat){- case 1: return_trace (u.format1.sanitize (c, glyph_count));- case 3: return_trace (u.format3.sanitize (c, glyph_count));+ case 1: hb_barrier (); return_trace (u.format1.sanitize (c, glyph_count));+ case 3: hb_barrier (); return_trace (u.format3.sanitize (c, glyph_count));default:return_trace (true);}}@@ -224,8 +224,9 @@ struct IndexSubtableunsigned int local_offset = cbdt_prime_len - u.header.imageDataOffset;switch (u.header.indexFormat){- case 1: return_trace (u.format1.add_offset (c, local_offset, size));+ case 1: hb_barrier (); return_trace (u.format1.add_offset (c, local_offset, size));case 3: {+ hb_barrier ();if (!u.format3.add_offset (c, local_offset, size))return_trace (false);if (!(num_glyphs & 0x01)) // Pad to 32-bit alignment if needed.@@ -252,6 +253,7 @@ struct IndexSubtableswitch (u.header.indexFormat){case 1: {+ hb_barrier ();for (unsigned int i = 0; i < num_missing; i++){if (unlikely (!u.format1.add_offset (c, local_offset, size)))@@ -261,6 +263,7 @@ struct IndexSubtablereturn_trace (true);}case 3: {+ hb_barrier ();for (unsigned int i = 0; i < num_missing; i++){if (unlikely (!u.format3.add_offset (c, local_offset, size)))@@ -303,8 +306,8 @@ struct IndexSubtableTRACE_SERIALIZE (this);switch (u.header.indexFormat){- case 1: return_trace (u.format1.add_offset (c, local_offset, size));- case 3: return_trace (u.format3.add_offset (c, local_offset, size));+ case 1: hb_barrier (); return_trace (u.format1.add_offset (c, local_offset, size));+ case 3: hb_barrier (); return_trace (u.format3.add_offset (c, local_offset, size));// TODO: Implement tables 2, 4, 5case 2: // Should be a no-op.case 4: case 5: // Handle sparse cases.@@ -329,8 +332,8 @@ struct IndexSubtable*format = u.header.imageFormat;switch (u.header.indexFormat){- case 1: return u.format1.get_image_data (idx, offset, length);- case 3: return u.format3.get_image_data (idx, offset, length);+ case 1: hb_barrier (); return u.format1.get_image_data (idx, offset, length);+ case 3: hb_barrier (); return u.format3.get_image_data (idx, offset, length);default: return false;}}@@ -882,10 +885,10 @@ struct CBDT{float x_scale = upem / (float) strike.ppemX;float y_scale = upem / (float) strike.ppemY;- extents->x_bearing = roundf (extents->x_bearing * x_scale);- extents->y_bearing = roundf (extents->y_bearing * y_scale);- extents->width = roundf (extents->width * x_scale);- extents->height = roundf (extents->height * y_scale);+ extents->x_bearing = hb_clamp_to<hb_position_t> (roundf (extents->x_bearing * x_scale));+ extents->y_bearing = hb_clamp_to<hb_position_t> (roundf (extents->y_bearing * y_scale));+ extents->width = hb_clamp_to<hb_position_t> (roundf (extents->width * x_scale));+ extents->height = hb_clamp_to<hb_position_t> (roundf (extents->height * y_scale));}return true;diff --git a/thirdparty/harfbuzz/src/OT/Color/COLR/COLR.hh b/thirdparty/harfbuzz/src/OT/Color/COLR/COLR.hhindex 62d3a3ce1b8..fef0fc79076 100644--- a/thirdparty/harfbuzz/src/OT/Color/COLR/COLR.hh+++ b/thirdparty/harfbuzz/src/OT/Color/COLR/COLR.hh@@ -35,6 +35,7 @@#include "../../../hb-paint.hh"#include "../../../hb-paint-bounded.hh"#include "../../../hb-paint-extents.hh"+#include "../../../hb-depend-data.hh"#include "../CPAL/CPAL.hh"@@ -119,6 +120,14 @@ public:hb_font_destroy (font);}+ static unsigned+ color_alpha (hb_color_t color, float alpha)+ {+ /* Font-supplied alpha is F2DOT14 plus variation deltas, so it can be+ * negative or greater than one; converting that to unsigned is UB. */+ return roundf (hb_color_get_alpha (color) * hb_clamp (alpha, 0.f, 1.f));+ }+hb_color_t get_color (unsigned int color_index, float alpha, hb_bool_t *is_foreground){hb_color_t color = foreground;@@ -136,7 +145,7 @@ public:return HB_COLOR (hb_color_get_blue (color),hb_color_get_green (color),hb_color_get_red (color),- hb_color_get_alpha (color) * alpha);+ color_alpha (color, alpha));}inline void recurse (const Paint &paint);@@ -219,6 +228,58 @@ struct hb_colrv1_closure_context_t :{}};++struct hb_colrv1_depend_context_t :+ hb_dispatch_context_t<hb_colrv1_depend_context_t>+{+ template <typename T>+ return_t dispatch (const T &obj)+ {+ if (unlikely (nesting_level_left == 0))+ return hb_empty_t ();++ if (paint_visited (&obj))+ return hb_empty_t ();++ nesting_level_left--;+ obj.dependv1 (this);+ nesting_level_left++;+ return hb_empty_t ();+ }+ static return_t default_return_value () { return hb_empty_t (); }++ bool paint_visited (const void *paint)+ {+ hb_codepoint_t delta = (hb_codepoint_t) ((uintptr_t) paint - (uintptr_t) colr);+ if (visited_paint.in_error() || visited_paint.has (delta))+ return true;++ visited_paint.add (delta);+ if (unlikely (visited_paint.in_error ()))+ depend_data->fail ();+ return false;+ }++ const COLR* get_colr_table () const+ { return colr; }++ public:+ const COLR *colr;+ hb_depend_data_builder_t *depend_data;+ hb_set_t visited_paint;+ unsigned nesting_level_left;+ hb_codepoint_t source_gid;++ hb_colrv1_depend_context_t (const COLR *colr_,+ hb_depend_data_builder_t *depend_data_,+ unsigned nesting_level_left_ = HB_MAX_NESTING_LEVEL) :+ colr (colr_),+ depend_data (depend_data_),+ nesting_level_left (nesting_level_left_),+ source_gid (0)+ {}+};+struct LayerRecord{operator hb_ot_color_layer_t () const { return {glyphId, colorIdx}; }@@ -280,6 +341,9 @@ struct Variablereturn_trace (c->embed (this));}+ void dependv1 (hb_colrv1_depend_context_t* c) const+ { value.dependv1 (c); }+void closurev1 (hb_colrv1_closure_context_t* c) const{c->num_var_idxes = 0;@@ -329,6 +393,12 @@ struct Variablevalue.get_color_stop (c, stop, varIdxBase, instancer);}+ void get_solid_color (hb_paint_context_t *c,+ hb_bool_t *is_foreground, hb_color_t *color) const+ {+ value.get_solid_color (c, varIdxBase, is_foreground, color);+ }+hb_paint_extend_t get_extend () const{return value.get_extend ();@@ -355,6 +425,9 @@ struct NoVariablereturn_trace (c->embed (this));}+ void dependv1 (hb_colrv1_depend_context_t* c) const+ { value.dependv1 (c); }+void closurev1 (hb_colrv1_closure_context_t* c) const{ value.closurev1 (c); }@@ -384,6 +457,12 @@ struct NoVariablevalue.get_color_stop (c, stop, VarIdx::NO_VARIATION, instancer);}+ void get_solid_color (hb_paint_context_t *c,+ hb_bool_t *is_foreground, hb_color_t *color) const+ {+ value.get_solid_color (c, VarIdx::NO_VARIATION, is_foreground, color);+ }+hb_paint_extend_t get_extend () const{return value.get_extend ();@@ -398,6 +477,8 @@ struct NoVariablestruct ColorStop{+ void dependv1 (hb_colrv1_depend_context_t * c) const {}+void closurev1 (hb_colrv1_closure_context_t* c) const{c->add_palette_index (paletteIndex);@@ -460,6 +541,8 @@ struct Extend : HBUINT8template <template<typename> class Var>struct ColorLine{+ void dependv1 (hb_colrv1_depend_context_t * c) const {}+void closurev1 (hb_colrv1_closure_context_t* c) const{for (const auto &stop : stops.iter ())@@ -555,44 +638,6 @@ struct ColorLine// or all of the specified modes.struct CompositeMode : HBUINT8{- enum {- // Porter-Duff modes- // https://www.w3.org/TR/compositing-1/#porterduffcompositingoperators- COMPOSITE_CLEAR = 0, // https://www.w3.org/TR/compositing-1/#porterduffcompositingoperators_clear- COMPOSITE_SRC = 1, // https://www.w3.org/TR/compositing-1/#porterduffcompositingoperators_src- COMPOSITE_DEST = 2, // https://www.w3.org/TR/compositing-1/#porterduffcompositingoperators_dst- COMPOSITE_SRC_OVER = 3, // https://www.w3.org/TR/compositing-1/#porterduffcompositingoperators_srcover- COMPOSITE_DEST_OVER = 4, // https://www.w3.org/TR/compositing-1/#porterduffcompositingoperators_dstover- COMPOSITE_SRC_IN = 5, // https://www.w3.org/TR/compositing-1/#porterduffcompositingoperators_srcin- COMPOSITE_DEST_IN = 6, // https://www.w3.org/TR/compositing-1/#porterduffcompositingoperators_dstin- COMPOSITE_SRC_OUT = 7, // https://www.w3.org/TR/compositing-1/#porterduffcompositingoperators_srcout- COMPOSITE_DEST_OUT = 8, // https://www.w3.org/TR/compositing-1/#porterduffcompositingoperators_dstout- COMPOSITE_SRC_ATOP = 9, // https://www.w3.org/TR/compositing-1/#porterduffcompositingoperators_srcatop- COMPOSITE_DEST_ATOP = 10, // https://www.w3.org/TR/compositing-1/#porterduffcompositingoperators_dstatop- COMPOSITE_XOR = 11, // https://www.w3.org/TR/compositing-1/#porterduffcompositingoperators_xor- COMPOSITE_PLUS = 12, // https://www.w3.org/TR/compositing-1/#porterduffcompositingoperators_plus-- // Blend modes- // https://www.w3.org/TR/compositing-1/#blending- COMPOSITE_SCREEN = 13, // https://www.w3.org/TR/compositing-1/#blendingscreen- COMPOSITE_OVERLAY = 14, // https://www.w3.org/TR/compositing-1/#blendingoverlay- COMPOSITE_DARKEN = 15, // https://www.w3.org/TR/compositing-1/#blendingdarken- COMPOSITE_LIGHTEN = 16, // https://www.w3.org/TR/compositing-1/#blendinglighten- COMPOSITE_COLOR_DODGE = 17, // https://www.w3.org/TR/compositing-1/#blendingcolordodge- COMPOSITE_COLOR_BURN = 18, // https://www.w3.org/TR/compositing-1/#blendingcolorburn- COMPOSITE_HARD_LIGHT = 19, // https://www.w3.org/TR/compositing-1/#blendinghardlight- COMPOSITE_SOFT_LIGHT = 20, // https://www.w3.org/TR/compositing-1/#blendingsoftlight- COMPOSITE_DIFFERENCE = 21, // https://www.w3.org/TR/compositing-1/#blendingdifference- COMPOSITE_EXCLUSION = 22, // https://www.w3.org/TR/compositing-1/#blendingexclusion- COMPOSITE_MULTIPLY = 23, // https://www.w3.org/TR/compositing-1/#blendingmultiply-- // Modes that, uniquely, do not operate on components- // https://www.w3.org/TR/compositing-1/#blendingnonseparable- COMPOSITE_HSL_HUE = 24, // https://www.w3.org/TR/compositing-1/#blendinghue- COMPOSITE_HSL_SATURATION = 25, // https://www.w3.org/TR/compositing-1/#blendingsaturation- COMPOSITE_HSL_COLOR = 26, // https://www.w3.org/TR/compositing-1/#blendingcolor- COMPOSITE_HSL_LUMINOSITY = 27, // https://www.w3.org/TR/compositing-1/#blendingluminosity- };public:DEFINE_SIZE_STATIC (1);};@@ -605,6 +650,8 @@ struct Affine2x3return_trace (c->check_struct (this));}+ void dependv1 (hb_colrv1_depend_context_t* c) const {}+void closurev1 (hb_colrv1_closure_context_t* c) const{ c->num_var_idxes = 6; }@@ -651,7 +698,8 @@ struct Affine2x3struct PaintColrLayers{- void closurev1 (hb_colrv1_closure_context_t* c) const;+ HB_INTERNAL void dependv1 (hb_colrv1_depend_context_t* c) const;+ HB_INTERNAL void closurev1 (hb_colrv1_closure_context_t* c) const;bool subset (hb_subset_context_t *c,const ItemVarStoreInstancer &instancer HB_UNUSED) const@@ -682,6 +730,7 @@ struct PaintColrLayersstruct PaintSolid{+ void dependv1 (hb_colrv1_depend_context_t* c) const {}void closurev1 (hb_colrv1_closure_context_t* c) const{c->add_palette_index (paletteIndex);@@ -712,15 +761,21 @@ struct PaintSolidreturn_trace (c->check_struct (this));}+ void get_solid_color (hb_paint_context_t *c, uint32_t varIdxBase,+ hb_bool_t *is_foreground, hb_color_t *color) const+ {+ *color = c->get_color (paletteIndex,+ alpha.to_float (c->instancer (varIdxBase, 0)),+ is_foreground);+ }+void paint_glyph (hb_paint_context_t *c, uint32_t varIdxBase) const{TRACE_PAINT (this);hb_bool_t is_foreground;hb_color_t color;- color = c->get_color (paletteIndex,- alpha.to_float (c->instancer (varIdxBase, 0)),- &is_foreground);+ get_solid_color (c, varIdxBase, &is_foreground, &color);c->funcs->color (c->data, is_foreground, color);}@@ -734,6 +789,8 @@ struct PaintSolidtemplate <template<typename> class Var>struct PaintLinearGradient{+ void dependv1 (hb_colrv1_depend_context_t* c) const {}+void closurev1 (hb_colrv1_closure_context_t* c) const{(this+colorLine).closurev1 (c);@@ -804,6 +861,8 @@ struct PaintLinearGradienttemplate <template<typename> class Var>struct PaintRadialGradient{+ void dependv1 (hb_colrv1_depend_context_t* c) const {}+void closurev1 (hb_colrv1_closure_context_t* c) const{(this+colorLine).closurev1 (c);@@ -822,10 +881,10 @@ struct PaintRadialGradient{out->x0 = x0 + (int) roundf (instancer (varIdxBase, 0));out->y0 = y0 + (int) roundf (instancer (varIdxBase, 1));- out->radius0 = radius0 + (unsigned) roundf (instancer (varIdxBase, 2));+ out->radius0 = hb_clamp ((int) radius0 + (int) roundf (instancer (varIdxBase, 2)), 0, 0xFFFF);out->x1 = x1 + (int) roundf (instancer (varIdxBase, 3));out->y1 = y1 + (int) roundf (instancer (varIdxBase, 4));- out->radius1 = radius1 + (unsigned) roundf (instancer (varIdxBase, 5));+ out->radius1 = hb_clamp ((int) radius1 + (int) roundf (instancer (varIdxBase, 5)), 0, 0xFFFF);}if (format == 7 && c->plan->all_axes_pinned)@@ -874,6 +933,8 @@ struct PaintRadialGradienttemplate <template<typename> class Var>struct PaintSweepGradient{+ void dependv1 (hb_colrv1_depend_context_t* c) const {}+void closurev1 (hb_colrv1_closure_context_t* c) const{(this+colorLine).closurev1 (c);@@ -938,7 +999,8 @@ struct PaintSweepGradient// Paint a non-COLR glyph, filled as indicated by paint.struct PaintGlyph{- void closurev1 (hb_colrv1_closure_context_t* c) const;+ HB_INTERNAL void dependv1 (hb_colrv1_depend_context_t* c) const;+ HB_INTERNAL void closurev1 (hb_colrv1_closure_context_t* c) const;bool subset (hb_subset_context_t *c,const ItemVarStoreInstancer &instancer) const@@ -960,17 +1022,7 @@ struct PaintGlyphreturn_trace (c->check_struct (this) && paint.sanitize (c, this));}- void paint_glyph (hb_paint_context_t *c) const- {- TRACE_PAINT (this);- c->funcs->push_inverse_font_transform (c->data, c->font);- c->funcs->push_clip_glyph (c->data, gid, c->font);- c->funcs->push_font_transform (c->data, c->font);- c->recurse (this+paint);- c->funcs->pop_transform (c->data);- c->funcs->pop_clip (c->data);- c->funcs->pop_transform (c->data);- }+ inline void paint_glyph (hb_paint_context_t *c) const;HBUINT8 format; /* format = 10 */Offset24To<Paint> paint; /* Offset (from beginning of PaintGlyph table) to Paint subtable. */@@ -981,7 +1033,8 @@ struct PaintGlyphstruct PaintColrGlyph{- void closurev1 (hb_colrv1_closure_context_t* c) const;+ HB_INTERNAL void dependv1 (hb_colrv1_depend_context_t* c) const;+ HB_INTERNAL void closurev1 (hb_colrv1_closure_context_t* c) const;bool subset (hb_subset_context_t *c,const ItemVarStoreInstancer &instancer HB_UNUSED) const@@ -1011,6 +1064,7 @@ struct PaintColrGlyphtemplate <template<typename> class Var>struct PaintTransform{+ HB_INTERNAL void dependv1 (hb_colrv1_depend_context_t* c) const;HB_INTERNAL void closurev1 (hb_colrv1_closure_context_t* c) const;bool subset (hb_subset_context_t *c,@@ -1050,6 +1104,7 @@ struct PaintTransformstruct PaintTranslate{+ HB_INTERNAL void dependv1 (hb_colrv1_depend_context_t* c) const;HB_INTERNAL void closurev1 (hb_colrv1_closure_context_t* c) const;bool subset (hb_subset_context_t *c,@@ -1099,6 +1154,7 @@ struct PaintTranslatestruct PaintScale{+ HB_INTERNAL void dependv1 (hb_colrv1_depend_context_t* c) const;HB_INTERNAL void closurev1 (hb_colrv1_closure_context_t* c) const;bool subset (hb_subset_context_t *c,@@ -1148,6 +1204,7 @@ struct PaintScalestruct PaintScaleAroundCenter{+ HB_INTERNAL void dependv1 (hb_colrv1_depend_context_t* c) const;HB_INTERNAL void closurev1 (hb_colrv1_closure_context_t* c) const;bool subset (hb_subset_context_t *c,@@ -1203,6 +1260,7 @@ struct PaintScaleAroundCenterstruct PaintScaleUniform{+ HB_INTERNAL void dependv1 (hb_colrv1_depend_context_t* c) const;HB_INTERNAL void closurev1 (hb_colrv1_closure_context_t* c) const;bool subset (hb_subset_context_t *c,@@ -1247,6 +1305,7 @@ struct PaintScaleUniformstruct PaintScaleUniformAroundCenter{+ HB_INTERNAL void dependv1 (hb_colrv1_depend_context_t* c) const;HB_INTERNAL void closurev1 (hb_colrv1_closure_context_t* c) const;bool subset (hb_subset_context_t *c,@@ -1299,6 +1358,7 @@ struct PaintScaleUniformAroundCenterstruct PaintRotate{+ HB_INTERNAL void dependv1 (hb_colrv1_depend_context_t* c) const;HB_INTERNAL void closurev1 (hb_colrv1_closure_context_t* c) const;bool subset (hb_subset_context_t *c,@@ -1343,6 +1403,7 @@ struct PaintRotatestruct PaintRotateAroundCenter{+ HB_INTERNAL void dependv1 (hb_colrv1_depend_context_t* c) const;HB_INTERNAL void closurev1 (hb_colrv1_closure_context_t* c) const;bool subset (hb_subset_context_t *c,@@ -1395,6 +1456,7 @@ struct PaintRotateAroundCenterstruct PaintSkew{+ HB_INTERNAL void dependv1 (hb_colrv1_depend_context_t* c) const;HB_INTERNAL void closurev1 (hb_colrv1_closure_context_t* c) const;bool subset (hb_subset_context_t *c,@@ -1444,6 +1506,7 @@ struct PaintSkewstruct PaintSkewAroundCenter{+ HB_INTERNAL void dependv1 (hb_colrv1_depend_context_t* c) const;HB_INTERNAL void closurev1 (hb_colrv1_closure_context_t* c) const;bool subset (hb_subset_context_t *c,@@ -1499,7 +1562,8 @@ struct PaintSkewAroundCenterstruct PaintComposite{- void closurev1 (hb_colrv1_closure_context_t* c) const;+ HB_INTERNAL void dependv1 (hb_colrv1_depend_context_t* c) const;+ HB_INTERNAL void closurev1 (hb_colrv1_closure_context_t* c) const;bool subset (hb_subset_context_t *c,const ItemVarStoreInstancer &instancer) const@@ -1526,11 +1590,49 @@ struct PaintCompositevoid paint_glyph (hb_paint_context_t *c) const{TRACE_PAINT (this);+ hb_paint_composite_mode_t composite_mode;+ switch ((unsigned int) mode)+ {+ case HB_PAINT_COMPOSITE_MODE_CLEAR:+ case HB_PAINT_COMPOSITE_MODE_SRC:+ case HB_PAINT_COMPOSITE_MODE_DEST:+ case HB_PAINT_COMPOSITE_MODE_SRC_OVER:+ case HB_PAINT_COMPOSITE_MODE_DEST_OVER:+ case HB_PAINT_COMPOSITE_MODE_SRC_IN:+ case HB_PAINT_COMPOSITE_MODE_DEST_IN:+ case HB_PAINT_COMPOSITE_MODE_SRC_OUT:+ case HB_PAINT_COMPOSITE_MODE_DEST_OUT:+ case HB_PAINT_COMPOSITE_MODE_SRC_ATOP:+ case HB_PAINT_COMPOSITE_MODE_DEST_ATOP:+ case HB_PAINT_COMPOSITE_MODE_XOR:+ case HB_PAINT_COMPOSITE_MODE_PLUS:+ case HB_PAINT_COMPOSITE_MODE_SCREEN:+ case HB_PAINT_COMPOSITE_MODE_OVERLAY:+ case HB_PAINT_COMPOSITE_MODE_DARKEN:+ case HB_PAINT_COMPOSITE_MODE_LIGHTEN:+ case HB_PAINT_COMPOSITE_MODE_COLOR_DODGE:+ case HB_PAINT_COMPOSITE_MODE_COLOR_BURN:+ case HB_PAINT_COMPOSITE_MODE_HARD_LIGHT:+ case HB_PAINT_COMPOSITE_MODE_SOFT_LIGHT:+ case HB_PAINT_COMPOSITE_MODE_DIFFERENCE:+ case HB_PAINT_COMPOSITE_MODE_EXCLUSION:+ case HB_PAINT_COMPOSITE_MODE_MULTIPLY:+ case HB_PAINT_COMPOSITE_MODE_HSL_HUE:+ case HB_PAINT_COMPOSITE_MODE_HSL_SATURATION:+ case HB_PAINT_COMPOSITE_MODE_HSL_COLOR:+ case HB_PAINT_COMPOSITE_MODE_HSL_LUMINOSITY:+ composite_mode = (hb_paint_composite_mode_t) (unsigned int) mode;+ break;+ default:+ composite_mode = HB_PAINT_COMPOSITE_MODE_CLEAR;+ break;+ }+c->funcs->push_group_for (c->data, HB_PAINT_COMPOSITE_MODE_SRC_OVER);c->recurse (this+backdrop);- c->funcs->push_group_for (c->data, (hb_paint_composite_mode_t) (int) mode);+ c->funcs->push_group_for (c->data, composite_mode);c->recurse (this+src);- c->funcs->pop_group (c->data, (hb_paint_composite_mode_t) (int) mode);+ c->funcs->pop_group (c->data, composite_mode);c->funcs->pop_group (c->data, HB_PAINT_COMPOSITE_MODE_SRC_OVER);}@@ -1602,10 +1704,10 @@ struct ClipBoxFormat2 : Variable<ClipBoxFormat1>value.get_clip_box(clip_box, instancer);if (instancer){- clip_box.xMin += roundf (instancer (varIdxBase, 0));- clip_box.yMin += roundf (instancer (varIdxBase, 1));- clip_box.xMax += roundf (instancer (varIdxBase, 2));- clip_box.yMax += roundf (instancer (varIdxBase, 3));+ clip_box.xMin = hb_saturate_add (clip_box.xMin, hb_clamp_to<int> (roundf (instancer (varIdxBase, 0))));+ clip_box.yMin = hb_saturate_add (clip_box.yMin, hb_clamp_to<int> (roundf (instancer (varIdxBase, 1))));+ clip_box.xMax = hb_saturate_add (clip_box.xMax, hb_clamp_to<int> (roundf (instancer (varIdxBase, 2))));+ clip_box.yMax = hb_saturate_add (clip_box.yMax, hb_clamp_to<int> (roundf (instancer (varIdxBase, 3))));}}@@ -1620,8 +1722,8 @@ struct ClipBox{TRACE_SUBSET (this);switch (u.format.v) {- case 1: return_trace (u.format1.subset (c, instancer, VarIdx::NO_VARIATION));- case 2: return_trace (u.format2.subset (c, instancer));+ case 1: hb_barrier (); return_trace (u.format1.subset (c, instancer, VarIdx::NO_VARIATION));+ case 2: hb_barrier (); return_trace (u.format2.subset (c, instancer));default:return_trace (c->default_return_value ());}}@@ -1629,7 +1731,7 @@ struct ClipBoxvoid closurev1 (hb_colrv1_closure_context_t* c) const{switch (u.format.v) {- case 2: u.format2.closurev1 (c); return;+ case 2: hb_barrier (); u.format2.closurev1 (c); return;default:return;}}@@ -1640,8 +1742,8 @@ struct ClipBoxif (unlikely (!c->may_dispatch (this, &u.format.v))) return c->no_dispatch_return_value ();TRACE_DISPATCH (this, u.format.v);switch (u.format.v) {- case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));- case 2: return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));+ case 1: hb_barrier (); return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));+ case 2: hb_barrier (); return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));default:return_trace (c->default_return_value ());}}@@ -1652,9 +1754,11 @@ struct ClipBoxClipBoxData clip_box;switch (u.format.v) {case 1:+ hb_barrier ();u.format1.get_clip_box (clip_box, instancer);break;case 2:+ hb_barrier ();u.format2.get_clip_box (clip_box, instancer);break;default:@@ -1663,8 +1767,8 @@ struct ClipBoxextents->x_bearing = clip_box.xMin;extents->y_bearing = clip_box.yMax;- extents->width = clip_box.xMax - clip_box.xMin;- extents->height = clip_box.yMin - clip_box.yMax;+ extents->width = hb_saturate_sub (clip_box.xMax, clip_box.xMin);+ extents->height = hb_saturate_sub (clip_box.yMin, clip_box.yMax);return true;}@@ -1850,42 +1954,52 @@ struct Paintif (unlikely (!c->may_dispatch (this, &u.format.v))) return c->no_dispatch_return_value ();TRACE_DISPATCH (this, u.format.v);switch (u.format.v) {- case 1: return_trace (c->dispatch (u.paintformat1, std::forward<Ts> (ds)...));- case 2: return_trace (c->dispatch (u.paintformat2, std::forward<Ts> (ds)...));- case 3: return_trace (c->dispatch (u.paintformat3, std::forward<Ts> (ds)...));- case 4: return_trace (c->dispatch (u.paintformat4, std::forward<Ts> (ds)...));- case 5: return_trace (c->dispatch (u.paintformat5, std::forward<Ts> (ds)...));- case 6: return_trace (c->dispatch (u.paintformat6, std::forward<Ts> (ds)...));- case 7: return_trace (c->dispatch (u.paintformat7, std::forward<Ts> (ds)...));- case 8: return_trace (c->dispatch (u.paintformat8, std::forward<Ts> (ds)...));- case 9: return_trace (c->dispatch (u.paintformat9, std::forward<Ts> (ds)...));- case 10: return_trace (c->dispatch (u.paintformat10, std::forward<Ts> (ds)...));- case 11: return_trace (c->dispatch (u.paintformat11, std::forward<Ts> (ds)...));- case 12: return_trace (c->dispatch (u.paintformat12, std::forward<Ts> (ds)...));- case 13: return_trace (c->dispatch (u.paintformat13, std::forward<Ts> (ds)...));- case 14: return_trace (c->dispatch (u.paintformat14, std::forward<Ts> (ds)...));- case 15: return_trace (c->dispatch (u.paintformat15, std::forward<Ts> (ds)...));- case 16: return_trace (c->dispatch (u.paintformat16, std::forward<Ts> (ds)...));- case 17: return_trace (c->dispatch (u.paintformat17, std::forward<Ts> (ds)...));- case 18: return_trace (c->dispatch (u.paintformat18, std::forward<Ts> (ds)...));- case 19: return_trace (c->dispatch (u.paintformat19, std::forward<Ts> (ds)...));- case 20: return_trace (c->dispatch (u.paintformat20, std::forward<Ts> (ds)...));- case 21: return_trace (c->dispatch (u.paintformat21, std::forward<Ts> (ds)...));- case 22: return_trace (c->dispatch (u.paintformat22, std::forward<Ts> (ds)...));- case 23: return_trace (c->dispatch (u.paintformat23, std::forward<Ts> (ds)...));- case 24: return_trace (c->dispatch (u.paintformat24, std::forward<Ts> (ds)...));- case 25: return_trace (c->dispatch (u.paintformat25, std::forward<Ts> (ds)...));- case 26: return_trace (c->dispatch (u.paintformat26, std::forward<Ts> (ds)...));- case 27: return_trace (c->dispatch (u.paintformat27, std::forward<Ts> (ds)...));- case 28: return_trace (c->dispatch (u.paintformat28, std::forward<Ts> (ds)...));- case 29: return_trace (c->dispatch (u.paintformat29, std::forward<Ts> (ds)...));- case 30: return_trace (c->dispatch (u.paintformat30, std::forward<Ts> (ds)...));- case 31: return_trace (c->dispatch (u.paintformat31, std::forward<Ts> (ds)...));- case 32: return_trace (c->dispatch (u.paintformat32, std::forward<Ts> (ds)...));+ case 1: hb_barrier (); return_trace (c->dispatch (u.paintformat1, std::forward<Ts> (ds)...));+ case 2: hb_barrier (); return_trace (c->dispatch (u.paintformat2, std::forward<Ts> (ds)...));+ case 3: hb_barrier (); return_trace (c->dispatch (u.paintformat3, std::forward<Ts> (ds)...));+ case 4: hb_barrier (); return_trace (c->dispatch (u.paintformat4, std::forward<Ts> (ds)...));+ case 5: hb_barrier (); return_trace (c->dispatch (u.paintformat5, std::forward<Ts> (ds)...));+ case 6: hb_barrier (); return_trace (c->dispatch (u.paintformat6, std::forward<Ts> (ds)...));+ case 7: hb_barrier (); return_trace (c->dispatch (u.paintformat7, std::forward<Ts> (ds)...));+ case 8: hb_barrier (); return_trace (c->dispatch (u.paintformat8, std::forward<Ts> (ds)...));+ case 9: hb_barrier (); return_trace (c->dispatch (u.paintformat9, std::forward<Ts> (ds)...));+ case 10: hb_barrier (); return_trace (c->dispatch (u.paintformat10, std::forward<Ts> (ds)...));+ case 11: hb_barrier (); return_trace (c->dispatch (u.paintformat11, std::forward<Ts> (ds)...));+ case 12: hb_barrier (); return_trace (c->dispatch (u.paintformat12, std::forward<Ts> (ds)...));+ case 13: hb_barrier (); return_trace (c->dispatch (u.paintformat13, std::forward<Ts> (ds)...));+ case 14: hb_barrier (); return_trace (c->dispatch (u.paintformat14, std::forward<Ts> (ds)...));+ case 15: hb_barrier (); return_trace (c->dispatch (u.paintformat15, std::forward<Ts> (ds)...));+ case 16: hb_barrier (); return_trace (c->dispatch (u.paintformat16, std::forward<Ts> (ds)...));+ case 17: hb_barrier (); return_trace (c->dispatch (u.paintformat17, std::forward<Ts> (ds)...));+ case 18: hb_barrier (); return_trace (c->dispatch (u.paintformat18, std::forward<Ts> (ds)...));+ case 19: hb_barrier (); return_trace (c->dispatch (u.paintformat19, std::forward<Ts> (ds)...));+ case 20: hb_barrier (); return_trace (c->dispatch (u.paintformat20, std::forward<Ts> (ds)...));+ case 21: hb_barrier (); return_trace (c->dispatch (u.paintformat21, std::forward<Ts> (ds)...));+ case 22: hb_barrier (); return_trace (c->dispatch (u.paintformat22, std::forward<Ts> (ds)...));+ case 23: hb_barrier (); return_trace (c->dispatch (u.paintformat23, std::forward<Ts> (ds)...));+ case 24: hb_barrier (); return_trace (c->dispatch (u.paintformat24, std::forward<Ts> (ds)...));+ case 25: hb_barrier (); return_trace (c->dispatch (u.paintformat25, std::forward<Ts> (ds)...));+ case 26: hb_barrier (); return_trace (c->dispatch (u.paintformat26, std::forward<Ts> (ds)...));+ case 27: hb_barrier (); return_trace (c->dispatch (u.paintformat27, std::forward<Ts> (ds)...));+ case 28: hb_barrier (); return_trace (c->dispatch (u.paintformat28, std::forward<Ts> (ds)...));+ case 29: hb_barrier (); return_trace (c->dispatch (u.paintformat29, std::forward<Ts> (ds)...));+ case 30: hb_barrier (); return_trace (c->dispatch (u.paintformat30, std::forward<Ts> (ds)...));+ case 31: hb_barrier (); return_trace (c->dispatch (u.paintformat31, std::forward<Ts> (ds)...));+ case 32: hb_barrier (); return_trace (c->dispatch (u.paintformat32, std::forward<Ts> (ds)...));default:return_trace (c->default_return_value ());}}+ bool get_solid_color (hb_paint_context_t *c,+ hb_bool_t *is_foreground, hb_color_t *color) const+ {+ switch (u.format.v) {+ case 2: hb_barrier (); u.paintformat2.get_solid_color (c, is_foreground, color); return true;+ case 3: hb_barrier (); u.paintformat3.get_solid_color (c, is_foreground, color); return true;+ default: return false;+ }+ }+protected:union {struct { HBUINT8 v; } format;@@ -2115,7 +2229,7 @@ struct COLRhb_array_t<const LayerRecord> all_layers = (this+layersZ).as_array (numLayers);hb_array_t<const LayerRecord> glyph_layers = all_layers.sub_array (record.firstLayerIdx,record.numLayers);- if (count)+ if (count && layers){+ glyph_layers.sub_array (start_offset, count)| hb_sink (hb_array (layers, *count))@@ -2178,6 +2292,12 @@ struct COLRbool is_valid () { return colr.get_blob ()->length; }+ void depend (hb_depend_data_builder_t *depend_data) const+ {+ if (!has_data ()) return;+ colr->depend (depend_data);+ }+void closure_glyphs (hb_codepoint_t glyph,hb_set_t *related_ids /* OUT */) const{ colr->closure_glyphs (glyph, related_ids); }@@ -2239,6 +2359,35 @@ struct COLRmutable hb_atomic_t<hb_colr_scratch_t *> cached_scratch;};+ void depend (hb_depend_data_builder_t *depend_data) const+ {+ // v0+ hb_array_t<const BaseGlyphRecord> baseGlyphs = (this+baseGlyphsZ).as_array (numBaseGlyphs);+ for (const BaseGlyphRecord &record : baseGlyphs)+ {+ auto glyph_layers = (this+layersZ).as_array (numLayers).sub_array (record.firstLayerIdx,+ record.numLayers);+ for (const LayerRecord layer : glyph_layers)+ depend_data->add_depend(record.glyphId, HB_OT_TAG_COLR, layer.glyphId);+ }++ if (!has_v1_data())+ return;++ // v1+ hb_colrv1_depend_context_t c (this, depend_data);+ const BaseGlyphList &baseglyph_paintrecords = this+baseGlyphList;++ for (const BaseGlyphPaintRecord &baseglyph_paintrecord: baseglyph_paintrecords.iter ())+ {+ c.source_gid = baseglyph_paintrecord.glyphId;+ c.visited_paint.clear ();++ const Paint &paint = &baseglyph_paintrecords+baseglyph_paintrecord.paint;+ paint.dispatch (&c);+ }+ }+void closure_glyphs (hb_codepoint_t glyph,hb_set_t *related_ids /* OUT */) const{@@ -2405,10 +2554,11 @@ struct COLRconst BaseGlyphPaintRecord* get_base_glyph_paintrecord (hb_codepoint_t gid) const{- const BaseGlyphPaintRecord* record = &(this+baseGlyphList).bsearch ((unsigned) gid);- if ((record && (hb_codepoint_t) record->glyphId != gid))- record = nullptr;- return record;+ const BaseGlyphList &list = this+baseGlyphList;+ unsigned int i;+ if (!list.bfind ((unsigned) gid, &i))+ return nullptr;+ return &list[i];}bool downgrade_to_V0 (const hb_set_t &glyphset) const@@ -2473,9 +2623,17 @@ struct COLR}else{+ /* avar2 partial instancing: cull unreachable regions. */+ hb_set_t dead_regions;+ if (c->plan->has_avar2)+ var_store.collect_dead_regions (c->plan->axes_old_index_tag_map,+ c->plan->avar2_reachable_ranges,+ dead_regions);+if (unlikely (!out->varStore.serialize_serialize (c->serializer,&var_store,- c->plan->colrv1_varstore_inner_maps.as_array ())))+ c->plan->colrv1_varstore_inner_maps.as_array (),+ dead_regions.get_population () ? &dead_regions : nullptr)))return_trace (false);}@@ -2580,8 +2738,8 @@ struct COLR* after instancing */if (!subset_varstore (c, colr_prime)) return_trace (false);- ItemVarStoreInstancer instancer (get_var_store_ptr (),- get_delta_set_index_map_ptr (),+ ItemVarStoreInstancer instancer (c->plan->normalized_coords ? get_var_store_ptr () : nullptr,+ c->plan->normalized_coords ? get_delta_set_index_map_ptr () : nullptr,c->plan->normalized_coords.as_array ());if (!colr_prime->baseGlyphList.serialize_subset (c, baseGlyphList, this, instancer))@@ -2637,12 +2795,7 @@ struct COLRextents->height = 0;}else- {- extents->x_bearing = e.xmin;- extents->y_bearing = e.ymax;- extents->width = e.xmax - e.xmin;- extents->height = e.ymin - e.ymax;- }+ *extents = e.to_glyph_extents ();return ret;}@@ -2700,19 +2853,10 @@ struct COLR// COLRv1 glyphbool is_bounded = true;+ hb_glyph_extents_t extents = {};if (clip){- hb_glyph_extents_t extents;- if (get_clip (glyph, &extents, instancer))- {- font->scale_glyph_extents (&extents);- c.funcs->push_clip_rectangle (c.data,- extents.x_bearing,- extents.y_bearing + extents.height,- extents.x_bearing + extents.width,- extents.y_bearing);- }- else+ if (!get_clip (glyph, &extents, instancer)){clip = false;is_bounded = false;@@ -2735,14 +2879,21 @@ struct COLRc.funcs->push_font_transform (c.data, font);+ if (clip)+ c.funcs->push_clip_rectangle (c.data,+ (float) extents.x_bearing,+ (float) extents.y_bearing + extents.height,+ (float) extents.x_bearing + extents.width,+ (float) extents.y_bearing);+if (is_bounded)c.recurse (*paint);- c.funcs->pop_transform (c.data);-if (clip)c.funcs->pop_clip (c.data);+ c.funcs->pop_transform (c.data);+return true;}}@@ -2756,9 +2907,7 @@ struct COLR{hb_bool_t is_foreground;hb_color_t color = c.get_color (r.colorIdx, 1., &is_foreground);- c.funcs->push_clip_glyph (c.data, r.glyphId, c.font);- c.funcs->color (c.data, is_foreground, color);- c.funcs->pop_clip (c.data);+ c.funcs->fill_glyph (c.data, r.glyphId, c.font, is_foreground, color);}return true;@@ -2800,6 +2949,32 @@ hb_paint_context_t::recurse (const Paint &paint)depth_left++;}+void PaintGlyph::paint_glyph (hb_paint_context_t *c) const+{+ TRACE_PAINT (this);++ hb_bool_t is_foreground;+ hb_color_t color;+ /* Optimize cases that can use a simple fill-glyph operation. */+ if (likely (c->depth_left > 0 && c->edge_count > 0) &&+ (this+paint).get_solid_color (c, &is_foreground, &color))+ {+ c->edge_count--;+ c->funcs->push_inverse_font_transform (c->data, c->font);+ c->funcs->fill_glyph (c->data, gid, c->font, is_foreground, color);+ c->funcs->pop_transform (c->data);+ return;+ }++ c->funcs->push_inverse_font_transform (c->data, c->font);+ c->funcs->push_clip_glyph (c->data, gid, c->font);+ c->funcs->push_font_transform (c->data, c->font);+ c->recurse (this+paint);+ c->funcs->pop_transform (c->data);+ c->funcs->pop_clip (c->data);+ c->funcs->pop_transform (c->data);+}+void PaintColrLayers::paint_glyph (hb_paint_context_t *c) const{TRACE_PAINT (this);@@ -2839,10 +3014,10 @@ void PaintColrGlyph::paint_glyph (hb_paint_context_t *c) constif (has_clip_box)c->funcs->push_clip_rectangle (c->data,- extents.x_bearing,- extents.y_bearing + extents.height,- extents.x_bearing + extents.width,- extents.y_bearing);+ (float) extents.x_bearing,+ (float) extents.y_bearing + extents.height,+ (float) extents.x_bearing + extents.width,+ (float) extents.y_bearing);if (paint)c->recurse (*paint);diff --git a/thirdparty/harfbuzz/src/OT/Color/COLR/colrv1-closure.hh b/thirdparty/harfbuzz/src/OT/Color/COLR/colrv1-closure.hhindex 9ed0aa5632a..29269210427 100644--- a/thirdparty/harfbuzz/src/OT/Color/COLR/colrv1-closure.hh+++ b/thirdparty/harfbuzz/src/OT/Color/COLR/colrv1-closure.hh@@ -42,7 +42,7 @@ HB_INTERNAL void PaintColrLayers::closurev1 (hb_colrv1_closure_context_t* c) conconst LayerList &paint_offset_lists = c->get_colr_table ()->get_layerList ();for (unsigned i = firstLayerIndex; i < firstLayerIndex + numLayers; i++){- const Paint &paint = std::addressof (paint_offset_lists) + paint_offset_lists[i];+ const Paint &paint = paint_offset_lists.get_paint (i);paint.dispatch (c);}}diff --git a/thirdparty/harfbuzz/src/OT/Color/COLR/colrv1-depend.hh b/thirdparty/harfbuzz/src/OT/Color/COLR/colrv1-depend.hhnew file mode 100644index 00000000000..e27f6cf7595--- /dev/null+++ b/thirdparty/harfbuzz/src/OT/Color/COLR/colrv1-depend.hh@@ -0,0 +1,132 @@+/*+ * Copyright © 2025 Skef Iterum+ *+ * 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.+ *+ */++#ifndef OT_COLOR_COLR_COLRV1_DEPEND_HH+#define OT_COLOR_COLR_COLRV1_DEPEND_HH++#include "../../../hb-open-type.hh"+#include "COLR.hh"++/*+ * COLR -- Color+ * https://docs.microsoft.com/en-us/typography/opentype/spec/colr+ */+namespace OT {+++HB_INTERNAL void PaintColrLayers::dependv1 (hb_colrv1_depend_context_t* c) const+{+ const LayerList &paint_offset_lists = c->get_colr_table ()->get_layerList ();+ for (unsigned i = firstLayerIndex; i < firstLayerIndex + numLayers; i++)+ {+ const Paint &paint = paint_offset_lists.get_paint (i);+ paint.dispatch (c);+ }+}++HB_INTERNAL void PaintGlyph::dependv1 (hb_colrv1_depend_context_t* c) const+{+ // PaintGlyph (Format 10) references glyph outlines (from glyf/CFF), not paint graphs.+ // Self-reference is valid per OpenType spec: a base glyph can reference its own+ // outline as geometry to fill. This is not a dependency in the traditional sense+ // since the outline is part of the same glyph data, so we skip it.+ if (gid != c->source_gid)+ c->depend_data->add_depend(c->source_gid, HB_OT_TAG_COLR, gid);+ (this+paint).dispatch (c);+}++HB_INTERNAL void PaintColrGlyph::dependv1 (hb_colrv1_depend_context_t* c) const+{+ const COLR *colr_table = c->get_colr_table ();+ const BaseGlyphPaintRecord* baseglyph_paintrecord = colr_table->get_base_glyph_paintrecord (gid);+ if (!baseglyph_paintrecord) return;+ c->depend_data->add_depend(c->source_gid, HB_OT_TAG_COLR, gid);++ const BaseGlyphList &baseglyph_list = colr_table->get_baseglyphList ();+ (&baseglyph_list+baseglyph_paintrecord->paint).dispatch (c);+}++template <template<typename> class Var>+HB_INTERNAL void PaintTransform<Var>::dependv1 (hb_colrv1_depend_context_t* c) const+{+ (this+src).dispatch (c);+}++HB_INTERNAL void PaintTranslate::dependv1 (hb_colrv1_depend_context_t* c) const+{+ (this+src).dispatch (c);+}++HB_INTERNAL void PaintScale::dependv1 (hb_colrv1_depend_context_t* c) const+{+ (this+src).dispatch (c);+}++HB_INTERNAL void PaintScaleAroundCenter::dependv1 (hb_colrv1_depend_context_t* c) const+{+ (this+src).dispatch (c);+}++HB_INTERNAL void PaintScaleUniform::dependv1 (hb_colrv1_depend_context_t* c) const+{+ (this+src).dispatch (c);+}++HB_INTERNAL void PaintScaleUniformAroundCenter::dependv1 (hb_colrv1_depend_context_t* c) const+{+ (this+src).dispatch (c);+}++HB_INTERNAL void PaintRotate::dependv1 (hb_colrv1_depend_context_t* c) const+{+ (this+src).dispatch (c);+}++HB_INTERNAL void PaintRotateAroundCenter::dependv1 (hb_colrv1_depend_context_t* c) const+{+ (this+src).dispatch (c);+}++HB_INTERNAL void PaintSkew::dependv1 (hb_colrv1_depend_context_t* c) const+{+ (this+src).dispatch (c);+}++HB_INTERNAL void PaintSkewAroundCenter::dependv1 (hb_colrv1_depend_context_t* c) const+{+ (this+src).dispatch (c);+}++HB_INTERNAL void PaintComposite::dependv1 (hb_colrv1_depend_context_t* c) const+{+ (this+src).dispatch (c);+ (this+backdrop).dispatch (c);+}+++} /* namespace OT */+++#endif /* OT_COLOR_COLR_COLRV1_DEPEND_HH */diff --git a/thirdparty/harfbuzz/src/OT/Color/CPAL/CPAL.hh b/thirdparty/harfbuzz/src/OT/Color/CPAL/CPAL.hhindex 9364fd93956..ade2c1f863b 100644--- a/thirdparty/harfbuzz/src/OT/Color/CPAL/CPAL.hh+++ b/thirdparty/harfbuzz/src/OT/Color/CPAL/CPAL.hh@@ -209,7 +209,7 @@ struct CPALhb_array_t<const BGRAColor> all_colors ((this+colorRecordsZ).arrayZ, numColorRecords);hb_array_t<const BGRAColor> palette_colors = all_colors.sub_array (start_index,numColors);- if (color_count)+ if (color_count && colors){+ palette_colors.sub_array (start_offset, color_count)| hb_sink (hb_array (colors, *color_count))diff --git a/thirdparty/harfbuzz/src/OT/Color/sbix/sbix.hh b/thirdparty/harfbuzz/src/OT/Color/sbix/sbix.hhindex b5760053a3c..9060df713d1 100644--- a/thirdparty/harfbuzz/src/OT/Color/sbix/sbix.hh+++ b/thirdparty/harfbuzz/src/OT/Color/sbix/sbix.hh@@ -337,18 +337,18 @@ struct sbix}extents->x_bearing = x_offset;- extents->y_bearing = png.IHDR.height + y_offset;- extents->width = png.IHDR.width;- extents->height = -1 * png.IHDR.height;+ extents->y_bearing = hb_clamp_to<hb_position_t> ((int64_t) (unsigned int) png.IHDR.height + y_offset);+ extents->width = (hb_position_t) (unsigned int) png.IHDR.width;+ extents->height = -(hb_position_t) (unsigned int) png.IHDR.height;/* Convert to font units. */if (strike_ppem && scale){float scale = font->face->get_upem () / (float) strike_ppem;- extents->x_bearing = roundf (extents->x_bearing * scale);- extents->y_bearing = roundf (extents->y_bearing * scale);- extents->width = roundf (extents->width * scale);- extents->height = roundf (extents->height * scale);+ extents->x_bearing = hb_clamp_to<hb_position_t> (roundf (extents->x_bearing * scale));+ extents->y_bearing = hb_clamp_to<hb_position_t> (roundf (extents->y_bearing * scale));+ extents->width = hb_clamp_to<hb_position_t> (roundf (extents->width * scale));+ extents->height = hb_clamp_to<hb_position_t> (roundf (extents->height * scale));}if (scale)diff --git a/thirdparty/harfbuzz/src/OT/Color/svg/svg.hh b/thirdparty/harfbuzz/src/OT/Color/svg/svg.hhindex b89894c64a8..e0096d5bf54 100644--- a/thirdparty/harfbuzz/src/OT/Color/svg/svg.hh+++ b/thirdparty/harfbuzz/src/OT/Color/svg/svg.hh@@ -499,7 +499,7 @@ parse_cache_entries_linear (const char *svg,while (p + name_len < gt){unsigned char c = (unsigned char) name[name_len];- if (!(isalnum (c) || c == '_' || c == '-' || c == ':'))+ if (!(ISALNUM (c) || c == '_' || c == '-' || c == ':'))break;name_len++;}diff --git a/thirdparty/harfbuzz/src/OT/Layout/Common/Coverage.hh b/thirdparty/harfbuzz/src/OT/Layout/Common/Coverage.hhindex 93ca1b2f7a7..492d09b3a30 100644--- a/thirdparty/harfbuzz/src/OT/Layout/Common/Coverage.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/Common/Coverage.hh@@ -67,11 +67,11 @@ struct Coveragehb_barrier ();switch (u.format.v){- case 1: return_trace (u.format1.sanitize (c));- case 2: return_trace (u.format2.sanitize (c));+ case 1: hb_barrier (); return_trace (u.format1.sanitize (c));+ case 2: hb_barrier (); return_trace (u.format2.sanitize (c));#ifndef HB_NO_BEYOND_64K- case 3: return_trace (u.format3.sanitize (c));- case 4: return_trace (u.format4.sanitize (c));+ case 3: hb_barrier (); return_trace (u.format3.sanitize (c));+ case 4: hb_barrier (); return_trace (u.format4.sanitize (c));#endifdefault:return_trace (true);}@@ -87,11 +87,11 @@ struct Coverageunsigned int get_coverage (hb_codepoint_t glyph_id) const{switch (u.format.v) {- case 1: return u.format1.get_coverage (glyph_id);- case 2: return u.format2.get_coverage (glyph_id);+ case 1: hb_barrier (); return u.format1.get_coverage (glyph_id);+ case 2: hb_barrier (); return u.format2.get_coverage (glyph_id);#ifndef HB_NO_BEYOND_64K- case 3: return u.format3.get_coverage (glyph_id);- case 4: return u.format4.get_coverage (glyph_id);+ case 3: hb_barrier (); return u.format3.get_coverage (glyph_id);+ case 4: hb_barrier (); return u.format4.get_coverage (glyph_id);#endifdefault:return NOT_COVERED;}@@ -129,11 +129,11 @@ struct Coverageunsigned get_population () const{switch (u.format.v) {- case 1: return u.format1.get_population ();- case 2: return u.format2.get_population ();+ case 1: hb_barrier (); return u.format1.get_population ();+ case 2: hb_barrier (); return u.format2.get_population ();#ifndef HB_NO_BEYOND_64K- case 3: return u.format3.get_population ();- case 4: return u.format4.get_population ();+ case 3: hb_barrier (); return u.format3.get_population ();+ case 4: hb_barrier (); return u.format4.get_population ();#endifdefault:return NOT_COVERED;}@@ -176,11 +176,11 @@ struct Coverageswitch (u.format.v){- case 1: return_trace (u.format1.serialize (c, glyphs));- case 2: return_trace (u.format2.serialize (c, glyphs));+ case 1: hb_barrier (); return_trace (u.format1.serialize (c, glyphs));+ case 2: hb_barrier (); return_trace (u.format2.serialize (c, glyphs));#ifndef HB_NO_BEYOND_64K- case 3: return_trace (u.format3.serialize (c, glyphs));- case 4: return_trace (u.format4.serialize (c, glyphs));+ case 3: hb_barrier (); return_trace (u.format3.serialize (c, glyphs));+ case 4: hb_barrier (); return_trace (u.format4.serialize (c, glyphs));#endifdefault:return_trace (false);}@@ -189,10 +189,13 @@ struct Coveragebool subset (hb_subset_context_t *c) const{TRACE_SUBSET (this);+ const hb_subset_plan_t *plan = c->plan;auto it =+ iter ()- | hb_take (c->plan->source->get_num_glyphs ())- | hb_map_retains_sorting (c->plan->glyph_map_gsub)+ | hb_take (plan->source->get_num_glyphs ())+ | hb_map_retains_sorting ([plan] (hb_codepoint_t g) {+ return plan->map_gsub_glyph (g);+ })| hb_filter ([] (hb_codepoint_t glyph) { return glyph != HB_MAP_VALUE_INVALID; });@@ -207,11 +210,11 @@ struct Coverage{switch (u.format.v){- case 1: return u.format1.intersects (glyphs);- case 2: return u.format2.intersects (glyphs);+ case 1: hb_barrier (); return u.format1.intersects (glyphs);+ case 2: hb_barrier (); return u.format2.intersects (glyphs);#ifndef HB_NO_BEYOND_64K- case 3: return u.format3.intersects (glyphs);- case 4: return u.format4.intersects (glyphs);+ case 3: hb_barrier (); return u.format3.intersects (glyphs);+ case 4: hb_barrier (); return u.format4.intersects (glyphs);#endifdefault:return false;}@@ -220,11 +223,11 @@ struct Coverage{switch (u.format.v){- case 1: return u.format1.intersects_coverage (glyphs, index);- case 2: return u.format2.intersects_coverage (glyphs, index);+ case 1: hb_barrier (); return u.format1.intersects_coverage (glyphs, index);+ case 2: hb_barrier (); return u.format2.intersects_coverage (glyphs, index);#ifndef HB_NO_BEYOND_64K- case 3: return u.format3.intersects_coverage (glyphs, index);- case 4: return u.format4.intersects_coverage (glyphs, index);+ case 3: hb_barrier (); return u.format3.intersects_coverage (glyphs, index);+ case 4: hb_barrier (); return u.format4.intersects_coverage (glyphs, index);#endifdefault:return false;}@@ -250,11 +253,11 @@ struct Coverage{switch (u.format.v){- case 1: return u.format1.collect_coverage (glyphs);- case 2: return u.format2.collect_coverage (glyphs);+ case 1: hb_barrier (); return u.format1.collect_coverage (glyphs);+ case 2: hb_barrier (); return u.format2.collect_coverage (glyphs);#ifndef HB_NO_BEYOND_64K- case 3: return u.format3.collect_coverage (glyphs);- case 4: return u.format4.collect_coverage (glyphs);+ case 3: hb_barrier (); return u.format3.collect_coverage (glyphs);+ case 4: hb_barrier (); return u.format4.collect_coverage (glyphs);#endifdefault:return false;}@@ -266,11 +269,11 @@ struct Coverage{switch (u.format.v){- case 1: return u.format1.intersect_set (glyphs, intersect_glyphs);- case 2: return u.format2.intersect_set (glyphs, intersect_glyphs);+ case 1: hb_barrier (); return u.format1.intersect_set (glyphs, intersect_glyphs);+ case 2: hb_barrier (); return u.format2.intersect_set (glyphs, intersect_glyphs);#ifndef HB_NO_BEYOND_64K- case 3: return u.format3.intersect_set (glyphs, intersect_glyphs);- case 4: return u.format4.intersect_set (glyphs, intersect_glyphs);+ case 3: hb_barrier (); return u.format3.intersect_set (glyphs, intersect_glyphs);+ case 4: hb_barrier (); return u.format4.intersect_set (glyphs, intersect_glyphs);#endifdefault:return ;}@@ -285,11 +288,11 @@ struct Coverageformat = c_.u.format.v;switch (format){- case 1: u.format1.init (c_.u.format1); return;- case 2: u.format2.init (c_.u.format2); return;+ case 1: hb_barrier (); u.format1.init (c_.u.format1); return;+ case 2: hb_barrier (); u.format2.init (c_.u.format2); return;#ifndef HB_NO_BEYOND_64K- case 3: u.format3.init (c_.u.format3); return;- case 4: u.format4.init (c_.u.format4); return;+ case 3: hb_barrier (); u.format3.init (c_.u.format3); return;+ case 4: hb_barrier (); u.format4.init (c_.u.format4); return;#endifdefault: return;}@@ -298,11 +301,11 @@ struct Coverage{switch (format){- case 1: return u.format1.__more__ ();- case 2: return u.format2.__more__ ();+ case 1: hb_barrier (); return u.format1.__more__ ();+ case 2: hb_barrier (); return u.format2.__more__ ();#ifndef HB_NO_BEYOND_64K- case 3: return u.format3.__more__ ();- case 4: return u.format4.__more__ ();+ case 3: hb_barrier (); return u.format3.__more__ ();+ case 4: hb_barrier (); return u.format4.__more__ ();#endifdefault:return false;}@@ -311,11 +314,11 @@ struct Coverage{switch (format){- case 1: u.format1.__next__ (); break;- case 2: u.format2.__next__ (); break;+ case 1: hb_barrier (); u.format1.__next__ (); break;+ case 2: hb_barrier (); u.format2.__next__ (); break;#ifndef HB_NO_BEYOND_64K- case 3: u.format3.__next__ (); break;- case 4: u.format4.__next__ (); break;+ case 3: hb_barrier (); u.format3.__next__ (); break;+ case 4: hb_barrier (); u.format4.__next__ (); break;#endifdefault: break;}@@ -327,11 +330,11 @@ struct Coverage{switch (format){- case 1: return u.format1.get_glyph ();- case 2: return u.format2.get_glyph ();+ case 1: hb_barrier (); return u.format1.get_glyph ();+ case 2: hb_barrier (); return u.format2.get_glyph ();#ifndef HB_NO_BEYOND_64K- case 3: return u.format3.get_glyph ();- case 4: return u.format4.get_glyph ();+ case 3: hb_barrier (); return u.format3.get_glyph ();+ case 4: hb_barrier (); return u.format4.get_glyph ();#endifdefault:return 0;}@@ -341,11 +344,11 @@ struct Coverageif (unlikely (format != o.format)) return true;switch (format){- case 1: return u.format1 != o.u.format1;- case 2: return u.format2 != o.u.format2;+ case 1: hb_barrier (); return u.format1 != o.u.format1;+ case 2: hb_barrier (); return u.format2 != o.u.format2;#ifndef HB_NO_BEYOND_64K- case 3: return u.format3 != o.u.format3;- case 4: return u.format4 != o.u.format4;+ case 3: hb_barrier (); return u.format3 != o.u.format3;+ case 4: hb_barrier (); return u.format4 != o.u.format4;#endifdefault:return false;}@@ -356,11 +359,11 @@ struct Coverageit.format = format;switch (format){- case 1: it.u.format1 = u.format1.__end__ (); break;- case 2: it.u.format2 = u.format2.__end__ (); break;+ case 1: hb_barrier (); it.u.format1 = u.format1.__end__ (); break;+ case 2: hb_barrier (); it.u.format2 = u.format2.__end__ (); break;#ifndef HB_NO_BEYOND_64K- case 3: it.u.format3 = u.format3.__end__ (); break;- case 4: it.u.format4 = u.format4.__end__ (); break;+ case 3: hb_barrier (); it.u.format3 = u.format3.__end__ (); break;+ case 4: hb_barrier (); it.u.format4 = u.format4.__end__ (); break;#endifdefault: break;}diff --git a/thirdparty/harfbuzz/src/OT/Layout/Common/CoverageFormat2.hh b/thirdparty/harfbuzz/src/OT/Layout/Common/CoverageFormat2.hhindex 19895cabb80..02fd29b2485 100644--- a/thirdparty/harfbuzz/src/OT/Layout/Common/CoverageFormat2.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/Common/CoverageFormat2.hh@@ -139,6 +139,19 @@ struct CoverageFormat2_4return false;}+ static void add_intersected_bits (hb_set_t &set, hb_codepoint_t base, uint64_t bits)+ { set.add_bits (base, bits); }++ template <typename IterableOut>+ static void add_intersected_bits (IterableOut&& out, hb_codepoint_t base, uint64_t bits)+ {+ while (bits)+ {+ out << base + hb_ctz (bits);+ bits &= bits - 1;+ }+ }+template <typename IterableOut,hb_requires (hb_is_sink_of (IterableOut, hb_codepoint_t))>void intersect_set (const hb_set_t &glyphs, IterableOut&& intersect_glyphs) const@@ -151,9 +164,18 @@ struct CoverageFormat2_4if (unlikely (range.first < last))break;last = range.last;- for (hb_codepoint_t g = range.first - 1;- glyphs.next (&g) && g <= last;)- intersect_glyphs << g;+ hb_codepoint_t cursor = range.first & -hb_bit_page_t::ELT_BITS;+ cursor = cursor ? cursor - 1 : HB_SET_VALUE_INVALID;+ uint64_t bits;+ while (glyphs.next_bits (&cursor, &bits) && cursor <= last)+ {+ if (range.first > cursor)+ bits &= UINT64_MAX << (range.first - cursor);+ unsigned int end = last - cursor;+ if (end < hb_bit_page_t::ELT_BITS - 1)+ bits &= (uint64_t (1) << (end + 1)) - 1;+ add_intersected_bits (intersect_glyphs, cursor, bits);+ }}}diff --git a/thirdparty/harfbuzz/src/OT/Layout/GDEF/GDEF.hh b/thirdparty/harfbuzz/src/OT/Layout/GDEF/GDEF.hhindex 01d72b1297d..acb047ac0e9 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GDEF/GDEF.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GDEF/GDEF.hh@@ -70,7 +70,7 @@ struct AttachListconst AttachPoint &points = this+attachPoint[index];- if (point_count)+ if (point_count && point_array){+ points.as_array ().sub_array (start_offset, point_count)| hb_sink (hb_array (point_array, *point_count))@@ -192,8 +192,8 @@ struct CaretValueFormat3const ItemVariationStore &var_store) const{return HB_DIRECTION_IS_HORIZONTAL (direction) ?- font->em_scale_x (coordinate) + (this+deviceTable).get_x_delta (font, var_store) :- font->em_scale_y (coordinate) + (this+deviceTable).get_y_delta (font, var_store);+ hb_saturate_add (font->em_scale_x (coordinate), (this+deviceTable).get_x_delta (font, var_store)) :+ hb_saturate_add (font->em_scale_y (coordinate), (this+deviceTable).get_y_delta (font, var_store));}bool subset (hb_subset_context_t *c) const@@ -253,9 +253,9 @@ struct CaretValueconst ItemVariationStore &var_store) const{switch (u.format.v) {- case 1: return u.format1.get_caret_value (font, direction);- case 2: return u.format2.get_caret_value (font, direction, glyph_id);- case 3: return u.format3.get_caret_value (font, direction, var_store);+ case 1: hb_barrier (); return u.format1.get_caret_value (font, direction);+ case 2: hb_barrier (); return u.format2.get_caret_value (font, direction, glyph_id);+ case 3: hb_barrier (); return u.format3.get_caret_value (font, direction, var_store);default:return 0;}}@@ -266,9 +266,9 @@ struct CaretValueif (unlikely (!c->may_dispatch (this, &u.format.v))) return c->no_dispatch_return_value ();TRACE_DISPATCH (this, u.format.v);switch (u.format.v) {- case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));- case 2: return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));- case 3: return_trace (c->dispatch (u.format3, std::forward<Ts> (ds)...));+ case 1: hb_barrier (); return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));+ case 2: hb_barrier (); return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));+ case 3: hb_barrier (); return_trace (c->dispatch (u.format3, std::forward<Ts> (ds)...));default:return_trace (c->default_return_value ());}}@@ -280,6 +280,7 @@ struct CaretValuecase 2:return;case 3:+ hb_barrier ();u.format3.collect_variation_indices (c);return;default: return;@@ -292,9 +293,9 @@ struct CaretValueif (!u.format.v.sanitize (c)) return_trace (false);hb_barrier ();switch (u.format.v) {- case 1: return_trace (u.format1.sanitize (c));- case 2: return_trace (u.format2.sanitize (c));- case 3: return_trace (u.format3.sanitize (c));+ case 1: hb_barrier (); return_trace (u.format1.sanitize (c));+ case 2: hb_barrier (); return_trace (u.format2.sanitize (c));+ case 3: hb_barrier (); return_trace (u.format3.sanitize (c));default:return_trace (true);}}@@ -320,7 +321,7 @@ struct LigGlyphunsigned *caret_count /* IN/OUT */,hb_position_t *caret_array /* OUT */) const{- if (caret_count)+ if (caret_count && caret_array){+ carets.as_array ().sub_array (start_offset, caret_count)| hb_map (hb_add (this))@@ -520,7 +521,7 @@ struct MarkGlyphSetsbool covers (unsigned int set_index, hb_codepoint_t glyph_id) const{switch (u.format.v) {- case 1: return u.format1.covers (set_index, glyph_id);+ case 1: hb_barrier (); return u.format1.covers (set_index, glyph_id);default:return false;}}@@ -529,7 +530,7 @@ struct MarkGlyphSetsvoid collect_coverage (hb_vector_t<set_t> &sets) const{switch (u.format.v) {- case 1: u.format1.collect_coverage (sets); return;+ case 1: hb_barrier (); u.format1.collect_coverage (sets); return;default:return;}}@@ -538,7 +539,7 @@ struct MarkGlyphSetshb_set_t& used_mark_sets /* OUT */) const{switch (u.format.v) {- case 1: u.format1.collect_used_mark_sets (glyph_set, used_mark_sets); return;+ case 1: hb_barrier (); u.format1.collect_used_mark_sets (glyph_set, used_mark_sets); return;default:return;}}@@ -547,7 +548,7 @@ struct MarkGlyphSets{TRACE_SUBSET (this);switch (u.format.v) {- case 1: return_trace (u.format1.subset (c));+ case 1: hb_barrier (); return_trace (u.format1.subset (c));default:return_trace (false);}}@@ -558,7 +559,7 @@ struct MarkGlyphSetsif (!u.format.v.sanitize (c)) return_trace (false);hb_barrier ();switch (u.format.v) {- case 1: return_trace (u.format1.sanitize (c));+ case 1: hb_barrier (); return_trace (u.format1.sanitize (c));default:return_trace (true);}}@@ -721,7 +722,7 @@ struct GDEFVersion1_2out->version.minor = 3;c->plan->has_gdef_varstore = true;} else if (subset_markglyphsetsdef) {- out->version.minor = 2;+ out->version.minor = 2;} else {out->version.minor = 0;c->serializer->revert (snapshot_version0);@@ -758,9 +759,9 @@ struct GDEFsize_t get_size () const{switch (u.version.major) {- case 1: return u.version1.get_size ();+ case 1: hb_barrier (); return u.version1.get_size ();#ifndef HB_NO_BEYOND_64K- case 2: return u.version2.get_size ();+ case 2: hb_barrier (); return u.version2.get_size ();#endifdefault: return u.version.static_size;}@@ -772,9 +773,9 @@ struct GDEFif (unlikely (!u.version.sanitize (c))) return_trace (false);hb_barrier ();switch (u.version.major) {- case 1: return_trace (u.version1.sanitize (c));+ case 1: hb_barrier (); return_trace (u.version1.sanitize (c));#ifndef HB_NO_BEYOND_64K- case 2: return_trace (u.version2.sanitize (c));+ case 2: hb_barrier (); return_trace (u.version2.sanitize (c));#endifdefault: return_trace (true);}@@ -783,9 +784,9 @@ struct GDEFbool subset (hb_subset_context_t *c) const{switch (u.version.major) {- case 1: return u.version1.subset (c);+ case 1: hb_barrier (); return u.version1.subset (c);#ifndef HB_NO_BEYOND_64K- case 2: return u.version2.subset (c);+ case 2: hb_barrier (); return u.version2.subset (c);#endifdefault: return false;}@@ -794,9 +795,9 @@ struct GDEFbool has_glyph_classes () const{switch (u.version.major) {- case 1: return u.version1.glyphClassDef != 0;+ case 1: hb_barrier (); return u.version1.glyphClassDef != 0;#ifndef HB_NO_BEYOND_64K- case 2: return u.version2.glyphClassDef != 0;+ case 2: hb_barrier (); return u.version2.glyphClassDef != 0;#endifdefault: return false;}@@ -804,9 +805,9 @@ struct GDEFconst ClassDef &get_glyph_class_def () const{switch (u.version.major) {- case 1: return this+u.version1.glyphClassDef;+ case 1: hb_barrier (); return this+u.version1.glyphClassDef;#ifndef HB_NO_BEYOND_64K- case 2: return this+u.version2.glyphClassDef;+ case 2: hb_barrier (); return this+u.version2.glyphClassDef;#endifdefault: return Null(ClassDef);}@@ -814,9 +815,9 @@ struct GDEFbool has_attach_list () const{switch (u.version.major) {- case 1: return u.version1.attachList != 0;+ case 1: hb_barrier (); return u.version1.attachList != 0;#ifndef HB_NO_BEYOND_64K- case 2: return u.version2.attachList != 0;+ case 2: hb_barrier (); return u.version2.attachList != 0;#endifdefault: return false;}@@ -824,9 +825,9 @@ struct GDEFconst AttachList &get_attach_list () const{switch (u.version.major) {- case 1: return this+u.version1.attachList;+ case 1: hb_barrier (); return this+u.version1.attachList;#ifndef HB_NO_BEYOND_64K- case 2: return this+u.version2.attachList;+ case 2: hb_barrier (); return this+u.version2.attachList;#endifdefault: return Null(AttachList);}@@ -834,9 +835,9 @@ struct GDEFbool has_lig_carets () const{switch (u.version.major) {- case 1: return u.version1.ligCaretList != 0;+ case 1: hb_barrier (); return u.version1.ligCaretList != 0;#ifndef HB_NO_BEYOND_64K- case 2: return u.version2.ligCaretList != 0;+ case 2: hb_barrier (); return u.version2.ligCaretList != 0;#endifdefault: return false;}@@ -844,9 +845,9 @@ struct GDEFconst LigCaretList &get_lig_caret_list () const{switch (u.version.major) {- case 1: return this+u.version1.ligCaretList;+ case 1: hb_barrier (); return this+u.version1.ligCaretList;#ifndef HB_NO_BEYOND_64K- case 2: return this+u.version2.ligCaretList;+ case 2: hb_barrier (); return this+u.version2.ligCaretList;#endifdefault: return Null(LigCaretList);}@@ -854,9 +855,9 @@ struct GDEFbool has_mark_attachment_types () const{switch (u.version.major) {- case 1: return u.version1.markAttachClassDef != 0;+ case 1: hb_barrier (); return u.version1.markAttachClassDef != 0;#ifndef HB_NO_BEYOND_64K- case 2: return u.version2.markAttachClassDef != 0;+ case 2: hb_barrier (); return u.version2.markAttachClassDef != 0;#endifdefault: return false;}@@ -864,9 +865,9 @@ struct GDEFconst ClassDef &get_mark_attach_class_def () const{switch (u.version.major) {- case 1: return this+u.version1.markAttachClassDef;+ case 1: hb_barrier (); return this+u.version1.markAttachClassDef;#ifndef HB_NO_BEYOND_64K- case 2: return this+u.version2.markAttachClassDef;+ case 2: hb_barrier (); return this+u.version2.markAttachClassDef;#endifdefault: return Null(ClassDef);}@@ -876,7 +877,7 @@ struct GDEFswitch (u.version.major) {case 1: return u.version.to_int () >= 0x00010002u && hb_barrier () && u.version1.markGlyphSetsDef != 0;#ifndef HB_NO_BEYOND_64K- case 2: return u.version2.markGlyphSetsDef != 0;+ case 2: hb_barrier (); return u.version2.markGlyphSetsDef != 0;#endifdefault: return false;}@@ -886,7 +887,7 @@ struct GDEFswitch (u.version.major) {case 1: return u.version.to_int () >= 0x00010002u && hb_barrier () ? this+u.version1.markGlyphSetsDef : Null(MarkGlyphSets);#ifndef HB_NO_BEYOND_64K- case 2: return this+u.version2.markGlyphSetsDef;+ case 2: hb_barrier (); return this+u.version2.markGlyphSetsDef;#endifdefault: return Null(MarkGlyphSets);}@@ -896,7 +897,7 @@ struct GDEFswitch (u.version.major) {case 1: return u.version.to_int () >= 0x00010003u && hb_barrier () && u.version1.varStore != 0;#ifndef HB_NO_BEYOND_64K- case 2: return u.version2.varStore != 0;+ case 2: hb_barrier (); return u.version2.varStore != 0;#endifdefault: return false;}@@ -906,7 +907,7 @@ struct GDEFswitch (u.version.major) {case 1: return u.version.to_int () >= 0x00010003u && hb_barrier () ? this+u.version1.varStore : Null(ItemVariationStore);#ifndef HB_NO_BEYOND_64K- case 2: return this+u.version2.varStore;+ case 2: hb_barrier (); return this+u.version2.varStore;#endifdefault: return Null(ItemVariationStore);}@@ -977,7 +978,39 @@ struct GDEF}#ifndef HB_NO_GDEF_CACHE- table->get_mark_glyph_sets ().collect_coverage (mark_glyph_sets);+ /* Flatten each mark set whose glyphs span fewer than PAGE_BITS+ * gids into a single bit-page biased at its first glyph, for+ * O(1) exact answers. Wider sets, or on allocation failure,+ * fall back to the table. */+ {+ hb_vector_t<hb_set_t> sets;+ table->get_mark_glyph_sets ().collect_coverage (sets);+ if (!sets.in_error () &&+ mark_glyph_set_bitmaps.resize (sets.length))+ for (unsigned i = 0; i < sets.length; i++)+ {+ auto &bitmap = mark_glyph_set_bitmaps.arrayZ[i];+ bitmap.bias = HB_SET_VALUE_INVALID;+ const auto &set = sets.arrayZ[i];+ if (unlikely (set.in_error ())) continue;+ hb_codepoint_t min_gid = HB_SET_VALUE_INVALID;+ hb_codepoint_t max_gid = HB_SET_VALUE_INVALID;+ hb_set_next (&set, &min_gid);+ hb_set_previous (&set, &max_gid);+ if (max_gid == HB_SET_VALUE_INVALID)+ continue;+ if (max_gid - min_gid >= hb_bit_page_t::PAGE_BITS)+ {+ /* Too wide for one page; a digest pre-filter instead. */+ for (hb_codepoint_t gid : set)+ bitmap.u.digest.add (gid);+ continue;+ }+ bitmap.bias = min_gid;+ for (hb_codepoint_t gid : set)+ bitmap.u.page.add (gid - min_gid);+ }+ }#endif}~accelerator_t () { table.destroy (); }@@ -1005,20 +1038,37 @@ struct GDEFHB_ALWAYS_INLINEbool mark_set_covers (unsigned int set_index, hb_codepoint_t glyph_id) const{- return#ifndef HB_NO_GDEF_CACHE- // We can access arrayZ directly because of sanitize_lookup_props() guarantee.- mark_glyph_sets.arrayZ[set_index].may_have (glyph_id) &&+ // We can access arrayZ directly because of sanitize_lookup_props() guarantee.+ const auto &bitmap = mark_glyph_set_bitmaps.arrayZ[set_index];+ if (likely (bitmap.bias != HB_SET_VALUE_INVALID))+ {+ hb_codepoint_t biased = glyph_id - bitmap.bias;+ return biased < hb_bit_page_t::PAGE_BITS &&+ bitmap.u.page.get (biased);+ }+ return mark_set_covers_slow (set_index, glyph_id);+#else+ return table->mark_set_covers (set_index, glyph_id);#endif- table->mark_set_covers (set_index, glyph_id)- ;}+#ifndef HB_NO_GDEF_CACHE+ HB_NEVER_INLINE+ bool mark_set_covers_slow (unsigned int set_index, hb_codepoint_t glyph_id) const+ {+ const auto &bitmap = mark_glyph_set_bitmaps.arrayZ[set_index];+ if (!bitmap.u.digest.may_have (glyph_id))+ return false;+ return table->mark_set_covers (set_index, glyph_id);+ }+#endif+unsigned sanitize_lookup_props (unsigned lookup_props) const{#ifndef HB_NO_GDEF_CACHEif (lookup_props & LookupFlag::UseMarkFilteringSet &&- (lookup_props >> 16) >= mark_glyph_sets.length)+ (lookup_props >> 16) >= mark_glyph_set_bitmaps.length){// Invalid mark filtering set index; unset the flag.lookup_props &= ~LookupFlag::UseMarkFilteringSet;@@ -1029,7 +1079,20 @@ struct GDEFhb_blob_ptr_t<GDEF> table;#ifndef HB_NO_GDEF_CACHE- hb_vector_t<hb_set_digest_t> mark_glyph_sets;+ struct mark_glyph_set_bitmap_t+ {+ /* Gid of the first bit (not page-aligned) for an exact one-page+ * set, or HB_SET_VALUE_INVALID; then digest is a pre-filter for+ * the table. The all-zeros state is valid for both members. */+ hb_codepoint_t bias = HB_SET_VALUE_INVALID;+ union u_t {+ u_t () : page () {}+ hb_bit_page_t page;+ hb_set_digest_t digest;+ } u;+ };++ hb_vector_t<mark_glyph_set_bitmap_t> mark_glyph_set_bitmaps;mutable hb_cache_t<21, 3> glyph_props_cache;static_assert (sizeof (glyph_props_cache) == 512, "");#endifdiff --git a/thirdparty/harfbuzz/src/OT/Layout/GPOS/Anchor.hh b/thirdparty/harfbuzz/src/OT/Layout/GPOS/Anchor.hhindex 1938803fa7c..48c509c25d2 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GPOS/Anchor.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GPOS/Anchor.hh@@ -27,9 +27,9 @@ struct Anchorif (!u.format.v.sanitize (c)) return_trace (false);hb_barrier ();switch (u.format.v) {- case 1: return_trace (u.format1.sanitize (c));- case 2: return_trace (u.format2.sanitize (c));- case 3: return_trace (u.format3.sanitize (c));+ case 1: hb_barrier (); return_trace (u.format1.sanitize (c));+ case 2: hb_barrier (); return_trace (u.format2.sanitize (c));+ case 3: hb_barrier (); return_trace (u.format3.sanitize (c));default:return_trace (true);}}@@ -39,9 +39,9 @@ struct Anchor{*x = *y = 0;switch (u.format.v) {- case 1: u.format1.get_anchor (c, glyph_id, x, y); return;- case 2: u.format2.get_anchor (c, glyph_id, x, y); return;- case 3: u.format3.get_anchor (c, glyph_id, x, y); return;+ case 1: hb_barrier (); u.format1.get_anchor (c, glyph_id, x, y); return;+ case 2: hb_barrier (); u.format2.get_anchor (c, glyph_id, x, y); return;+ case 3: hb_barrier (); u.format3.get_anchor (c, glyph_id, x, y); return;default: return;}}@@ -50,8 +50,9 @@ struct Anchor{TRACE_SUBSET (this);switch (u.format.v) {- case 1: return_trace (bool (reinterpret_cast<Anchor *> (u.format1.copy (c->serializer))));+ case 1: hb_barrier (); return_trace (bool (reinterpret_cast<Anchor *> (u.format1.copy (c->serializer))));case 2:+ hb_barrier ();if (c->plan->flags & HB_SUBSET_FLAGS_NO_HINTING){// AnchorFormat 2 just containins extra hinting information, so@@ -59,7 +60,7 @@ struct Anchorreturn_trace (bool (reinterpret_cast<Anchor *> (u.format1.copy (c->serializer))));}return_trace (bool (reinterpret_cast<Anchor *> (u.format2.copy (c->serializer))));- case 3: return_trace (u.format3.subset (c));+ case 3: hb_barrier (); return_trace (u.format3.subset (c));default:return_trace (false);}}@@ -70,6 +71,7 @@ struct Anchorcase 1: case 2:return;case 3:+ hb_barrier ();u.format3.collect_variation_indices (c);return;default: return;diff --git a/thirdparty/harfbuzz/src/OT/Layout/GPOS/CursivePos.hh b/thirdparty/harfbuzz/src/OT/Layout/GPOS/CursivePos.hhindex 38a29dd9ed5..e5e99cfaf6f 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GPOS/CursivePos.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GPOS/CursivePos.hh@@ -22,7 +22,7 @@ struct CursivePosif (unlikely (!c->may_dispatch (this, &u.format.v))) return c->no_dispatch_return_value ();TRACE_DISPATCH (this, u.format.v);switch (u.format.v) {- case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));+ case 1: hb_barrier (); return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));default:return_trace (c->default_return_value ());}}diff --git a/thirdparty/harfbuzz/src/OT/Layout/GPOS/CursivePosFormat1.hh b/thirdparty/harfbuzz/src/OT/Layout/GPOS/CursivePosFormat1.hhindex 3e2c15d5669..e3888c555c1 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GPOS/CursivePosFormat1.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GPOS/CursivePosFormat1.hh@@ -2,6 +2,7 @@#define OT_LAYOUT_GPOS_CURSIVEPOSFORMAT1_HH#include "Anchor.hh"+#include "../../../hb-limits.hh"namespace OT {namespace Layout {@@ -55,8 +56,12 @@ reverse_cursive_minor_offset (hb_glyph_position_t *pos,unsigned int len,unsigned int i,hb_direction_t direction,- unsigned int new_parent)+ unsigned int new_parent,+ unsigned nesting_level = 0){+ if (nesting_level > HB_MAX_NESTING_LEVEL)+ return;+int chain = pos[i].attach_chain(), type = pos[i].attach_type();if (likely (!chain || 0 == (type & ATTACH_TYPE_CURSIVE)))return;@@ -79,12 +84,12 @@ reverse_cursive_minor_offset (hb_glyph_position_t *pos,if (unlikely (reversed_chain != -chain))return;- reverse_cursive_minor_offset (pos, len, j, direction, new_parent);+ reverse_cursive_minor_offset (pos, len, j, direction, new_parent, nesting_level + 1);if (HB_DIRECTION_IS_HORIZONTAL (direction))- pos[j].y_offset = -pos[i].y_offset;+ pos[j].y_offset = hb_saturate_neg (pos[i].y_offset);else- pos[j].x_offset = -pos[i].x_offset;+ pos[j].x_offset = hb_saturate_neg (pos[i].x_offset);pos[j].attach_chain() = reversed_chain;pos[j].attach_type() = type;@@ -184,32 +189,32 @@ struct CursivePosFormat1/* Main-direction adjustment */switch (c->direction) {case HB_DIRECTION_LTR:- pos[i].x_advance = roundf (exit_x) + pos[i].x_offset;+ pos[i].x_advance = hb_saturate_add ((hb_position_t) roundf (exit_x), pos[i].x_offset);- d = roundf (entry_x) + pos[j].x_offset;- pos[j].x_advance -= d;- pos[j].x_offset -= d;+ d = hb_saturate_add ((hb_position_t) roundf (entry_x), pos[j].x_offset);+ pos[j].x_advance = hb_saturate_sub (pos[j].x_advance, d);+ pos[j].x_offset = hb_saturate_sub (pos[j].x_offset, d);break;case HB_DIRECTION_RTL:- d = roundf (exit_x) + pos[i].x_offset;- pos[i].x_advance -= d;- pos[i].x_offset -= d;+ d = hb_saturate_add ((hb_position_t) roundf (exit_x), pos[i].x_offset);+ pos[i].x_advance = hb_saturate_sub (pos[i].x_advance, d);+ pos[i].x_offset = hb_saturate_sub (pos[i].x_offset, d);- pos[j].x_advance = roundf (entry_x) + pos[j].x_offset;+ pos[j].x_advance = hb_saturate_add ((hb_position_t) roundf (entry_x), pos[j].x_offset);break;case HB_DIRECTION_TTB:- pos[i].y_advance = roundf (exit_y) + pos[i].y_offset;+ pos[i].y_advance = hb_saturate_add ((hb_position_t) roundf (exit_y), pos[i].y_offset);- d = roundf (entry_y) + pos[j].y_offset;- pos[j].y_advance -= d;- pos[j].y_offset -= d;+ d = hb_saturate_add ((hb_position_t) roundf (entry_y), pos[j].y_offset);+ pos[j].y_advance = hb_saturate_sub (pos[j].y_advance, d);+ pos[j].y_offset = hb_saturate_sub (pos[j].y_offset, d);break;case HB_DIRECTION_BTT:- d = roundf (exit_y) + pos[i].y_offset;- pos[i].y_advance -= d;- pos[i].y_offset -= d;+ d = hb_saturate_add ((hb_position_t) roundf (exit_y), pos[i].y_offset);+ pos[i].y_advance = hb_saturate_sub (pos[i].y_advance, d);+ pos[i].y_offset = hb_saturate_sub (pos[i].y_offset, d);- pos[j].y_advance = roundf (entry_y);+ pos[j].y_advance = (hb_position_t) roundf (entry_y);break;case HB_DIRECTION_INVALID:default:@@ -226,8 +231,8 @@ struct CursivePosFormat1* Arabic. */unsigned int child = i;unsigned int parent = j;- hb_position_t x_offset = roundf (entry_x - exit_x);- hb_position_t y_offset = roundf (entry_y - exit_y);+ hb_position_t x_offset = (hb_position_t) roundf (entry_x - exit_x);+ hb_position_t y_offset = (hb_position_t) roundf (entry_y - exit_y);if (!(c->lookup_props & LookupFlag::RightToLeft)){unsigned int k = child;diff --git a/thirdparty/harfbuzz/src/OT/Layout/GPOS/GPOS.hh b/thirdparty/harfbuzz/src/OT/Layout/GPOS/GPOS.hhindex 762c19eae5a..7b29fb01b14 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GPOS/GPOS.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GPOS/GPOS.hh@@ -101,14 +101,16 @@ propagate_attachment_offsets (hb_glyph_position_t *pos,if (type & GPOS_impl::ATTACH_TYPE_CURSIVE){if (HB_DIRECTION_IS_HORIZONTAL (direction))- pos[i].y_offset += pos[j].y_offset;+ pos[i].y_offset = hb_saturate_add (pos[i].y_offset, pos[j].y_offset);else- pos[i].x_offset += pos[j].x_offset;+ pos[i].x_offset = hb_saturate_add (pos[i].x_offset, pos[j].x_offset);}else /*if (type & GPOS_impl::ATTACH_TYPE_MARK)*/{- pos[i].x_offset += pos[j].x_offset;- pos[i].y_offset += pos[j].y_offset;+ if (HB_DIRECTION_IS_HORIZONTAL (direction))+ pos[i].x_offset = hb_saturate_add (pos[i].x_offset, pos[j].x_offset);+ else+ pos[i].y_offset = hb_saturate_add (pos[i].y_offset, pos[j].y_offset);// i is the position of the mark; j is the base.if (j < i)@@ -117,13 +119,13 @@ propagate_attachment_offsets (hb_glyph_position_t *pos,* And currently the only way in OpenType. */if (HB_DIRECTION_IS_FORWARD (direction))for (unsigned int k = j; k < i; k++) {- pos[i].x_offset -= pos[k].x_advance;- pos[i].y_offset -= pos[k].y_advance;+ pos[i].x_offset = hb_saturate_sub (pos[i].x_offset, pos[k].x_advance);+ pos[i].y_offset = hb_saturate_sub (pos[i].y_offset, pos[k].y_advance);}elsefor (unsigned int k = j + 1; k < i + 1; k++) {- pos[i].x_offset += pos[k].x_advance;- pos[i].y_offset += pos[k].y_advance;+ pos[i].x_offset = hb_saturate_add (pos[i].x_offset, pos[k].x_advance);+ pos[i].y_offset = hb_saturate_add (pos[i].y_offset, pos[k].y_advance);}}else // j > i@@ -132,13 +134,13 @@ propagate_attachment_offsets (hb_glyph_position_t *pos,* to a base after it in the logical order. */if (HB_DIRECTION_IS_FORWARD (direction))for (unsigned int k = i; k < j; k++) {- pos[i].x_offset += pos[k].x_advance;- pos[i].y_offset += pos[k].y_advance;+ pos[i].x_offset = hb_saturate_add (pos[i].x_offset, pos[k].x_advance);+ pos[i].y_offset = hb_saturate_add (pos[i].y_offset, pos[k].y_advance);}elsefor (unsigned int k = i + 1; k < j + 1; k++) {- pos[i].x_offset -= pos[k].x_advance;- pos[i].y_offset -= pos[k].y_advance;+ pos[i].x_offset = hb_saturate_sub (pos[i].x_offset, pos[k].x_advance);+ pos[i].y_offset = hb_saturate_sub (pos[i].y_offset, pos[k].y_advance);}}}@@ -191,7 +193,8 @@ GPOS::position_finish_offsets (hb_font_t *font, hb_buffer_t *buffer)* as it gets weird otherwise. */for (unsigned i = 0; i < len; i++)if (unlikely (pos[i].y_offset))- pos[i].x_offset += roundf (font->slant_xy * pos[i].y_offset);+ pos[i].x_offset = hb_clamp_to<hb_position_t> ((double) pos[i].x_offset ++ (double) roundf (font->slant_xy * pos[i].y_offset));}}diff --git a/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkArray.hh b/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkArray.hhindex 403a6a2bdfd..470651aa6e5 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkArray.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkArray.hh@@ -8,6 +8,29 @@ namespace OT {namespace Layout {namespace GPOS_impl {+static inline hb_position_t+resolve_cross_offset (const hb_glyph_position_t *pos,+ unsigned int len,+ unsigned int glyph_pos,+ hb_direction_t direction)+{+ bool horizontal = HB_DIRECTION_IS_HORIZONTAL (direction);+ hb_position_t offset = horizontal ? pos[glyph_pos].y_offset : pos[glyph_pos].x_offset;+ while (pos[glyph_pos].attach_type() & ATTACH_TYPE_CURSIVE)+ {+ int chain = pos[glyph_pos].attach_chain();+ if (!chain)+ break;+ unsigned int parent = (int) glyph_pos + chain;+ if (unlikely (parent >= len))+ break;+ glyph_pos = parent;+ offset = hb_saturate_add (offset,+ horizontal ? pos[glyph_pos].y_offset : pos[glyph_pos].x_offset);+ }+ return offset;+}+struct MarkArray : Array16Of<MarkRecord> /* Array of MarkRecords--in Coverage order */{bool sanitize (hb_sanitize_context_t *c) const@@ -46,16 +69,23 @@ struct MarkArray : Array16Of<MarkRecord> /* Array of MarkRecords--in Covec->buffer->idx, glyph_pos);}- hb_glyph_position_t &o = buffer->cur_pos();- o.attach_chain() = (int) glyph_pos - (int) buffer->idx;- if (o.attach_chain() != (int) glyph_pos - (int) buffer->idx)+ hb_position_t base_offset = resolve_cross_offset (buffer->pos, buffer->len, glyph_pos,+ buffer->props.direction);++ hb_glyph_position_t &mark = buffer->cur_pos();+ mark.attach_chain() = (int) glyph_pos - (int) buffer->idx;+ if (mark.attach_chain() != (int) glyph_pos - (int) buffer->idx){- o.attach_chain() = 0;+ mark.attach_chain() = 0;goto overflow;}- o.attach_type() = ATTACH_TYPE_MARK;- o.x_offset = roundf (base_x - mark_x);- o.y_offset = roundf (base_y - mark_y);+ mark.attach_type() = ATTACH_TYPE_MARK;+ mark.x_offset = roundf (base_x - mark_x);+ mark.y_offset = roundf (base_y - mark_y);+ if (HB_DIRECTION_IS_HORIZONTAL (buffer->props.direction))+ mark.y_offset = hb_saturate_add (mark.y_offset, base_offset);+ else+ mark.x_offset = hb_saturate_add (mark.x_offset, base_offset);buffer->scratch_flags |= HB_BUFFER_SCRATCH_FLAG_HAS_GPOS_ATTACHMENT;if (HB_BUFFER_MESSAGE_MORE && c->buffer->messaging ())diff --git a/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkBasePos.hh b/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkBasePos.hhindex 32476663b17..c0c9be9b1f5 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkBasePos.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkBasePos.hh@@ -25,9 +25,9 @@ struct MarkBasePosif (unlikely (!c->may_dispatch (this, &u.format.v))) return c->no_dispatch_return_value ();TRACE_DISPATCH (this, u.format.v);switch (u.format.v) {- case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));+ case 1: hb_barrier (); return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));#ifndef HB_NO_BEYOND_64K- case 2: return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));+ case 2: hb_barrier (); return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));#endifdefault:return_trace (c->default_return_value ());}diff --git a/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkLigPos.hh b/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkLigPos.hhindex 5c686f5764b..c3e56e2bfc8 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkLigPos.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkLigPos.hh@@ -25,9 +25,9 @@ struct MarkLigPosif (unlikely (!c->may_dispatch (this, &u.format.v))) return c->no_dispatch_return_value ();TRACE_DISPATCH (this, u.format.v);switch (u.format.v) {- case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));+ case 1: hb_barrier (); return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));#ifndef HB_NO_BEYOND_64K- case 2: return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));+ case 2: hb_barrier (); return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));#endifdefault:return_trace (c->default_return_value ());}diff --git a/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkLigPosFormat1.hh b/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkLigPosFormat1.hhindex 57dae77a9d0..5b1a93e388e 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkLigPosFormat1.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkLigPosFormat1.hh@@ -92,6 +92,17 @@ struct MarkLigPosFormat1_2const Coverage &get_coverage () const { return this+markCoverage; }+ static inline bool accept (hb_buffer_t *buffer, unsigned idx)+ {+ /* We only want to attach to the first of a MultipleSubst sequence,+ * which might have been ligated into a preceding ligature, and in that+ * case the mark should attach to that ligature.+ * https://github.com/harfbuzz/harfbuzz/issues/4969+ * Reject others... */+ return !_hb_glyph_info_multiplied (&buffer->info[idx]) ||+ 0 == _hb_glyph_info_get_lig_comp (&buffer->info[idx]);+ }+bool apply (hb_ot_apply_context_t *c) const{TRACE_APPLY (this);@@ -114,6 +125,13 @@ struct MarkLigPosFormat1_2{auto match = skippy_iter.match (buffer->info[j - 1]);if (match == skippy_iter.MATCH)+ {+ // https://github.com/harfbuzz/harfbuzz/issues/4124+ if (!accept (buffer, j - 1) &&+ NOT_COVERED == (this+ligatureCoverage).get_coverage (buffer->info[j - 1].codepoint))+ match = skippy_iter.SKIP;+ }+ if (match == skippy_iter.MATCH){c->last_base = (signed) j - 1;break;diff --git a/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkMarkPos.hh b/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkMarkPos.hhindex dbd8419ca92..ba1acc82ebb 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkMarkPos.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GPOS/MarkMarkPos.hh@@ -25,9 +25,9 @@ struct MarkMarkPosif (unlikely (!c->may_dispatch (this, &u.format.v))) return c->no_dispatch_return_value ();TRACE_DISPATCH (this, u.format.v);switch (u.format.v) {- case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));+ case 1: hb_barrier (); return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));#ifndef HB_NO_BEYOND_64K- case 2: return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));+ case 2: hb_barrier (); return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));#endifdefault:return_trace (c->default_return_value ());}diff --git a/thirdparty/harfbuzz/src/OT/Layout/GPOS/PairPos.hh b/thirdparty/harfbuzz/src/OT/Layout/GPOS/PairPos.hhindex 1b3b70090a5..765db3a24f2 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GPOS/PairPos.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GPOS/PairPos.hh@@ -28,11 +28,11 @@ struct PairPosif (unlikely (!c->may_dispatch (this, &u.format.v))) return c->no_dispatch_return_value ();TRACE_DISPATCH (this, u.format.v);switch (u.format.v) {- case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));- case 2: return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));+ case 1: hb_barrier (); return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));+ case 2: hb_barrier (); return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));#ifndef HB_NO_BEYOND_64K- case 3: return_trace (c->dispatch (u.format3, std::forward<Ts> (ds)...));- case 4: return_trace (c->dispatch (u.format4, std::forward<Ts> (ds)...));+ case 3: hb_barrier (); return_trace (c->dispatch (u.format3, std::forward<Ts> (ds)...));+ case 4: hb_barrier (); return_trace (c->dispatch (u.format4, std::forward<Ts> (ds)...));#endifdefault:return_trace (c->default_return_value ());}diff --git a/thirdparty/harfbuzz/src/OT/Layout/GPOS/PairPosFormat2.hh b/thirdparty/harfbuzz/src/OT/Layout/GPOS/PairPosFormat2.hhindex e7320b932da..88506dfb860 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GPOS/PairPosFormat2.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GPOS/PairPosFormat2.hh@@ -228,15 +228,15 @@ struct PairPosFormat2_4 : ValueBaseif (!backward){- dst1[i] += kern1;- dst2[i] += kern2;- dst2[i + 2] += kern2;+ dst1[i] = hb_saturate_add (dst1[i], kern1);+ dst2[i] = hb_saturate_add (dst2[i], kern2);+ dst2[i + 2] = hb_saturate_add (dst2[i + 2], kern2);}else{- dst1[i] += kern1;- dst1[i + 2] += src[i + 2] - kern2;- dst2[i] += kern2;+ dst1[i] = hb_saturate_add (dst1[i], kern1);+ dst1[i + 2] = hb_clamp_to<hb_position_t> ((int64_t) dst1[i + 2] + src[i + 2] - kern2);+ dst2[i] = hb_saturate_add (dst2[i], kern2);}applied_first = applied_second = kern != 0;diff --git a/thirdparty/harfbuzz/src/OT/Layout/GPOS/PosLookupSubTable.hh b/thirdparty/harfbuzz/src/OT/Layout/GPOS/PosLookupSubTable.hhindex c19fbc323ff..4238f98f4e1 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GPOS/PosLookupSubTable.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GPOS/PosLookupSubTable.hh@@ -37,15 +37,15 @@ struct PosLookupSubTable{TRACE_DISPATCH (this, lookup_type);switch (lookup_type) {- case Single: return_trace (u.single.dispatch (c, std::forward<Ts> (ds)...));- case Pair: return_trace (u.pair.dispatch (c, std::forward<Ts> (ds)...));- case Cursive: return_trace (u.cursive.dispatch (c, std::forward<Ts> (ds)...));- case MarkBase: return_trace (u.markBase.dispatch (c, std::forward<Ts> (ds)...));- case MarkLig: return_trace (u.markLig.dispatch (c, std::forward<Ts> (ds)...));- case MarkMark: return_trace (u.markMark.dispatch (c, std::forward<Ts> (ds)...));- case Context: return_trace (u.context.dispatch (c, std::forward<Ts> (ds)...));- case ChainContext: return_trace (u.chainContext.dispatch (c, std::forward<Ts> (ds)...));- case Extension: return_trace (u.extension.dispatch (c, std::forward<Ts> (ds)...));+ case Single: hb_barrier (); return_trace (u.single.dispatch (c, std::forward<Ts> (ds)...));+ case Pair: hb_barrier (); return_trace (u.pair.dispatch (c, std::forward<Ts> (ds)...));+ case Cursive: hb_barrier (); return_trace (u.cursive.dispatch (c, std::forward<Ts> (ds)...));+ case MarkBase: hb_barrier (); return_trace (u.markBase.dispatch (c, std::forward<Ts> (ds)...));+ case MarkLig: hb_barrier (); return_trace (u.markLig.dispatch (c, std::forward<Ts> (ds)...));+ case MarkMark: hb_barrier (); return_trace (u.markMark.dispatch (c, std::forward<Ts> (ds)...));+ case Context: hb_barrier (); return_trace (u.context.dispatch (c, std::forward<Ts> (ds)...));+ case ChainContext: hb_barrier (); return_trace (u.chainContext.dispatch (c, std::forward<Ts> (ds)...));+ case Extension: hb_barrier (); return_trace (u.extension.dispatch (c, std::forward<Ts> (ds)...));default: return_trace (c->default_return_value ());}}diff --git a/thirdparty/harfbuzz/src/OT/Layout/GPOS/SinglePos.hh b/thirdparty/harfbuzz/src/OT/Layout/GPOS/SinglePos.hhindex 30fc1aacda8..ddf25e6436c 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GPOS/SinglePos.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GPOS/SinglePos.hh@@ -51,13 +51,13 @@ struct SinglePosu.format.v = format;switch (u.format.v) {- case 1: u.format1.serialize (c,+ case 1: hb_barrier (); u.format1.serialize (c,src,glyph_val_iter_pairs,new_format,layout_variation_idx_delta_map);return;- case 2: u.format2.serialize (c,+ case 2: hb_barrier (); u.format2.serialize (c,src,glyph_val_iter_pairs,new_format,@@ -73,8 +73,8 @@ struct SinglePosif (unlikely (!c->may_dispatch (this, &u.format.v))) return c->no_dispatch_return_value ();TRACE_DISPATCH (this, u.format.v);switch (u.format.v) {- case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));- case 2: return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));+ case 1: hb_barrier (); return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));+ case 2: hb_barrier (); return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));default:return_trace (c->default_return_value ());}}diff --git a/thirdparty/harfbuzz/src/OT/Layout/GPOS/ValueFormat.hh b/thirdparty/harfbuzz/src/OT/Layout/GPOS/ValueFormat.hhindex e231c4d2fc6..b98b58032a0 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GPOS/ValueFormat.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GPOS/ValueFormat.hh@@ -102,15 +102,19 @@ struct ValueFormat : HBUINT16#endif;- if (format & xPlacement) glyph_pos.x_offset += font->em_scale_x (get_short (values++, &ret));- if (format & yPlacement) glyph_pos.y_offset += font->em_scale_y (get_short (values++, &ret));+ if (format & xPlacement)+ glyph_pos.x_offset = hb_saturate_add (glyph_pos.x_offset, font->em_scale_x (get_short (values++, &ret)));+ if (format & yPlacement)+ glyph_pos.y_offset = hb_saturate_add (glyph_pos.y_offset, font->em_scale_y (get_short (values++, &ret)));if (format & xAdvance) {- if (likely (horizontal)) glyph_pos.x_advance += font->em_scale_x (get_short (values, &ret));+ if (likely (horizontal))+ glyph_pos.x_advance = hb_saturate_add (glyph_pos.x_advance, font->em_scale_x (get_short (values, &ret)));values++;}/* y_advance values grow downward but font-space grows upward, hence negation */if (format & yAdvance) {- if (unlikely (!horizontal)) glyph_pos.y_advance -= font->em_scale_y (get_short (values, &ret));+ if (unlikely (!horizontal))+ glyph_pos.y_advance = hb_saturate_sub (glyph_pos.y_advance, font->em_scale_y (get_short (values, &ret)));values++;}@@ -127,23 +131,27 @@ struct ValueFormat : HBUINT16/* pixel -> fractional pixel */if (format & xPlaDevice){- if (use_x_device) glyph_pos.x_offset += get_device (values, &ret, base, c->sanitizer).get_x_delta (font, store, cache);+ if (use_x_device)+ glyph_pos.x_offset = hb_saturate_add (glyph_pos.x_offset, get_device (values, &ret, base, c->sanitizer).get_x_delta (font, store, cache));values++;}if (format & yPlaDevice){- if (use_y_device) glyph_pos.y_offset += get_device (values, &ret, base, c->sanitizer).get_y_delta (font, store, cache);+ if (use_y_device)+ glyph_pos.y_offset = hb_saturate_add (glyph_pos.y_offset, get_device (values, &ret, base, c->sanitizer).get_y_delta (font, store, cache));values++;}if (format & xAdvDevice){- if (horizontal && use_x_device) glyph_pos.x_advance += get_device (values, &ret, base, c->sanitizer).get_x_delta (font, store, cache);+ if (horizontal && use_x_device)+ glyph_pos.x_advance = hb_saturate_add (glyph_pos.x_advance, get_device (values, &ret, base, c->sanitizer).get_x_delta (font, store, cache));values++;}if (format & yAdvDevice){/* y_advance values grow downward but font-space grows upward, hence negation */- if (!horizontal && use_y_device) glyph_pos.y_advance -= get_device (values, &ret, base, c->sanitizer).get_y_delta (font, store, cache);+ if (!horizontal && use_y_device)+ glyph_pos.y_advance = hb_saturate_sub (glyph_pos.y_advance, get_device (values, &ret, base, c->sanitizer).get_y_delta (font, store, cache));values++;}return ret;diff --git a/thirdparty/harfbuzz/src/OT/Layout/GSUB/AlternateSet.hh b/thirdparty/harfbuzz/src/OT/Layout/GSUB/AlternateSet.hhindex 0437cff463b..9420f34602f 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GSUB/AlternateSet.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GSUB/AlternateSet.hh@@ -29,6 +29,13 @@ struct AlternateSetvoid closure (hb_closure_context_t *c) const{ c->output->add_array (alternates.arrayZ, alternates.len); }+ void depend (hb_depend_context_t *c, hb_codepoint_t source) const+ {+ + hb_iter (alternates)+ | hb_apply ([&] (const hb_codepoint_t &target) { c->depend_data->add_gsub_lookup (source, c->lookup_index, target); })+ ;+ }+void collect_glyphs (hb_collect_glyphs_context_t *c) const{ c->output->add_array (alternates.arrayZ, alternates.len); }@@ -82,7 +89,7 @@ struct AlternateSetunsigned *alternate_count /* IN/OUT. May be NULL. */,hb_codepoint_t *alternate_glyphs /* OUT. May be NULL. */) const{- if (alternates.len && alternate_count)+ if (alternates.len && alternate_count && alternate_glyphs){+ alternates.as_array ().sub_array (start_offset, alternate_count)| hb_sink (hb_array (alternate_glyphs, *alternate_count))diff --git a/thirdparty/harfbuzz/src/OT/Layout/GSUB/AlternateSubst.hh b/thirdparty/harfbuzz/src/OT/Layout/GSUB/AlternateSubst.hhindex 08b1dbbee72..ffe6432f2cc 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GSUB/AlternateSubst.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GSUB/AlternateSubst.hh@@ -26,9 +26,9 @@ struct AlternateSubstif (unlikely (!c->may_dispatch (this, &u.format.v))) return c->no_dispatch_return_value ();TRACE_DISPATCH (this, u.format.v);switch (u.format.v) {- case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));+ case 1: hb_barrier (); return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));#ifndef HB_NO_BEYOND_64K- case 2: return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));+ case 2: hb_barrier (); return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));#endifdefault:return_trace (c->default_return_value ());}@@ -46,7 +46,7 @@ struct AlternateSubstunsigned int format = 1;u.format.v = format;switch (u.format.v) {- case 1: return_trace (u.format1.serialize (c, glyphs, alternate_len_list, alternate_glyphs_list));+ case 1: hb_barrier (); return_trace (u.format1.serialize (c, glyphs, alternate_len_list, alternate_glyphs_list));default:return_trace (false);}}diff --git a/thirdparty/harfbuzz/src/OT/Layout/GSUB/AlternateSubstFormat1.hh b/thirdparty/harfbuzz/src/OT/Layout/GSUB/AlternateSubstFormat1.hhindex 294855907a7..8af1aa7a7ab 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GSUB/AlternateSubstFormat1.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GSUB/AlternateSubstFormat1.hh@@ -34,6 +34,19 @@ struct AlternateSubstFormat1_2bool may_have_non_1to1 () const{ return false; }+ void depend (hb_depend_context_t *c) const+ {+ // Filter by parent_active_glyphs like closure does+ + hb_zip (this+coverage, alternateSet)+ | hb_filter (c->parent_active_glyphs (), hb_first)+ | hb_apply ([&] (const hb_pair_t<hb_codepoint_t, const typename Types::template OffsetTo<AlternateSet<Types>>&> &_)+ {+ const AlternateSet<Types>& as = this+_.second;+ as.depend (c, _.first);+ })+ ;+ }+void closure (hb_closure_context_t *c) const{+ hb_zip (this+coverage, alternateSet)diff --git a/thirdparty/harfbuzz/src/OT/Layout/GSUB/GSUB.hh b/thirdparty/harfbuzz/src/OT/Layout/GSUB/GSUB.hhindex 900cf603e45..3d221b828ef 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GSUB/GSUB.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GSUB/GSUB.hh@@ -53,6 +53,7 @@ struct GSUB : GSUBGPOSstruct GSUB_accelerator_t : Layout::GSUB::accelerator_t {GSUB_accelerator_t (hb_face_t *face) : Layout::GSUB::accelerator_t (face) {}+ HB_INTERNAL void depend (hb_depend_data_builder_t *builder, hb_face_t *face) const;};diff --git a/thirdparty/harfbuzz/src/OT/Layout/GSUB/Ligature.hh b/thirdparty/harfbuzz/src/OT/Layout/GSUB/Ligature.hhindex dfa46b181ce..e99b1ded147 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GSUB/Ligature.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GSUB/Ligature.hh@@ -38,6 +38,40 @@ struct Ligaturec->output->add (ligGlyph);}+ void depend (hb_depend_context_t *c, hb_codepoint_t first) const+ {+ // Build the complete ligature set upfront before adding any edges+ hb_set_t complete_ligset;+ complete_ligset.add (first);+ + hb_iter (component) | hb_sink (complete_ligset);+ if (unlikely (complete_ligset.in_error ()))+ {+ c->depend_data->fail ();+ return;+ }++ bool ligset_created;+ hb_codepoint_t ligset_idx = c->depend_data->find_or_create_set (complete_ligset,+ &ligset_created);+ if (unlikely (ligset_idx == HB_CODEPOINT_INVALID))+ return;++ // Track whether any edge using this ligset_idx was actually added+ bool any_added = false;++ // Now add one edge for each glyph in the complete, immutable set+ + hb_iter (complete_ligset)+ | hb_apply ([&] (hb_codepoint_t gid) {+ if (c->depend_data->add_gsub_lookup (gid, c->lookup_index, ligGlyph, ligset_idx))+ any_added = true;+ })+ ;++ // If no edges were added, a newly allocated set is unused - free it for reuse+ if (!any_added && ligset_created)+ c->depend_data->discard_set (ligset_idx);+ }+void collect_glyphs (hb_collect_glyphs_context_t *c) const{c->input->add_array (component.arrayZ, component.get_length ());diff --git a/thirdparty/harfbuzz/src/OT/Layout/GSUB/LigatureSet.hh b/thirdparty/harfbuzz/src/OT/Layout/GSUB/LigatureSet.hhindex e3987947566..cefae5d4089 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GSUB/LigatureSet.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GSUB/LigatureSet.hh@@ -54,6 +54,14 @@ struct LigatureSet;}+ void depend (hb_depend_context_t *c, hb_codepoint_t first) const+ {+ + hb_iter (ligature)+ | hb_map (hb_add (this))+ | hb_apply ([&] (const Ligature<Types> &_) { _.depend (c, first); })+ ;+ }+void collect_glyphs (hb_collect_glyphs_context_t *c) const{+ hb_iter (ligature)diff --git a/thirdparty/harfbuzz/src/OT/Layout/GSUB/LigatureSubst.hh b/thirdparty/harfbuzz/src/OT/Layout/GSUB/LigatureSubst.hhindex 406d91ecae2..45e949299d2 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GSUB/LigatureSubst.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GSUB/LigatureSubst.hh@@ -26,9 +26,9 @@ struct LigatureSubstif (unlikely (!c->may_dispatch (this, &u.format.v))) return c->no_dispatch_return_value ();TRACE_DISPATCH (this, u.format.v);switch (u.format.v) {- case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));+ case 1: hb_barrier (); return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));#ifndef HB_NO_BEYOND_64K- case 2: return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));+ case 2: hb_barrier (); return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));#endifdefault:return_trace (c->default_return_value ());}@@ -49,7 +49,7 @@ struct LigatureSubstunsigned int format = 1;u.format.v = format;switch (u.format.v) {- case 1: return_trace (u.format1.serialize (c,+ case 1: hb_barrier (); return_trace (u.format1.serialize (c,first_glyphs,ligature_per_first_glyph_count_list,ligatures_list,diff --git a/thirdparty/harfbuzz/src/OT/Layout/GSUB/LigatureSubstFormat1.hh b/thirdparty/harfbuzz/src/OT/Layout/GSUB/LigatureSubstFormat1.hhindex 909ddca220f..759517ee88d 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GSUB/LigatureSubstFormat1.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GSUB/LigatureSubstFormat1.hh@@ -43,6 +43,18 @@ struct LigatureSubstFormat1_2bool may_have_non_1to1 () const{ return true; }+ void depend (hb_depend_context_t *c) const+ {+ + hb_zip (this+coverage, ligatureSet)+ | hb_filter (c->parent_active_glyphs (), hb_first)+ | hb_apply ([&] (const hb_pair_t<hb_codepoint_t, const typename Types::template OffsetTo<LigatureSet<Types>>&> &_)+ {+ const LigatureSet<Types>& ls = this+_.second;+ ls.depend (c, _.first);+ })+ ;+ }+void closure (hb_closure_context_t *c) const{+ hb_zip (this+coverage, ligatureSet)diff --git a/thirdparty/harfbuzz/src/OT/Layout/GSUB/MultipleSubst.hh b/thirdparty/harfbuzz/src/OT/Layout/GSUB/MultipleSubst.hhindex 2ff59ad9788..adfb20aa818 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GSUB/MultipleSubst.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GSUB/MultipleSubst.hh@@ -27,9 +27,9 @@ struct MultipleSubstif (unlikely (!c->may_dispatch (this, &u.format.v))) return c->no_dispatch_return_value ();TRACE_DISPATCH (this, u.format.v);switch (u.format.v) {- case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));+ case 1: hb_barrier (); return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));#ifndef HB_NO_BEYOND_64K- case 2: return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));+ case 2: hb_barrier (); return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));#endifdefault:return_trace (c->default_return_value ());}@@ -45,7 +45,7 @@ struct MultipleSubstunsigned int format = 1;u.format.v = format;switch (u.format.v) {- case 1: return_trace (u.format1.serialize (c, it));+ case 1: hb_barrier (); return_trace (u.format1.serialize (c, it));default:return_trace (false);}}diff --git a/thirdparty/harfbuzz/src/OT/Layout/GSUB/MultipleSubstFormat1.hh b/thirdparty/harfbuzz/src/OT/Layout/GSUB/MultipleSubstFormat1.hhindex 441d4dee0cb..a4e85dda561 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GSUB/MultipleSubstFormat1.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GSUB/MultipleSubstFormat1.hh@@ -44,6 +44,19 @@ struct MultipleSubstFormat1_2;}+ void depend (hb_depend_context_t *c) const+ {+ // Filter by parent_active_glyphs like closure does+ + hb_zip (this+coverage, sequence)+ | hb_filter (c->parent_active_glyphs (), hb_first)+ | hb_apply ([&] (const hb_pair_t<hb_codepoint_t, const typename Types::template OffsetTo<Sequence<Types>>&> &_)+ {+ const Sequence<Types>& s = this+_.second;+ s.depend (c, _.first);+ })+ ;+ }+void closure_lookups (hb_closure_lookups_context_t *c) const {}void collect_glyphs (hb_collect_glyphs_context_t *c) constdiff --git a/thirdparty/harfbuzz/src/OT/Layout/GSUB/ReverseChainSingleSubst.hh b/thirdparty/harfbuzz/src/OT/Layout/GSUB/ReverseChainSingleSubst.hhindex e33148d770b..0643a4870a2 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GSUB/ReverseChainSingleSubst.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GSUB/ReverseChainSingleSubst.hh@@ -23,7 +23,7 @@ struct ReverseChainSingleSubstif (unlikely (!c->may_dispatch (this, &u.format.v))) return c->no_dispatch_return_value ();TRACE_DISPATCH (this, u.format.v);switch (u.format.v) {- case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));+ case 1: hb_barrier (); return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));default:return_trace (c->default_return_value ());}}diff --git a/thirdparty/harfbuzz/src/OT/Layout/GSUB/ReverseChainSingleSubstFormat1.hh b/thirdparty/harfbuzz/src/OT/Layout/GSUB/ReverseChainSingleSubstFormat1.hhindex 1f598cc40f7..48d7d62c3a6 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GSUB/ReverseChainSingleSubstFormat1.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GSUB/ReverseChainSingleSubstFormat1.hh@@ -67,6 +67,76 @@ struct ReverseChainSingleSubstFormat1bool may_have_non_1to1 () const{ return false; }+ void depend (hb_depend_context_t *c) const {+ // Filter by intersects and parent_active_glyphs like closure does+ if (!intersects (c->glyphs)) return;++ const auto &lookahead = StructAfter<decltype (lookaheadX)> (backtrack);+ const auto &substitute = StructAfter<decltype (substituteX)> (lookahead);++ /* Build context set from backtrack and lookahead coverages.+ * ReverseChainSingleSubst has contextual requirements - the substitution+ * only fires when backtrack and lookahead glyphs are present. */+ hb_set_t context_glyphs;++ /* Add glyphs from backtrack coverages */+ unsigned int count = backtrack.len;+ for (unsigned int i = 0; i < count; i++)+ {+ hb_set_t back_glyphs;+ (this+backtrack[i]).intersect_set (*c->glyphs, back_glyphs);+ if (back_glyphs.get_population () == 1)+ context_glyphs.add (back_glyphs.get_min ());+ else if (back_glyphs.get_population () > 1)+ {+ hb_codepoint_t set_idx = c->depend_data->find_or_create_context_set (back_glyphs);+ if (unlikely (set_idx == HB_CODEPOINT_INVALID))+ return;+ context_glyphs.add (HB_DEPEND_CONTEXT_SET_FLAG | set_idx);+ }+ }++ /* Add glyphs from lookahead coverages */+ count = lookahead.len;+ for (unsigned int i = 0; i < count; i++)+ {+ hb_set_t look_glyphs;+ (this+lookahead[i]).intersect_set (*c->glyphs, look_glyphs);+ if (look_glyphs.get_population () == 1)+ context_glyphs.add (look_glyphs.get_min ());+ else if (look_glyphs.get_population () > 1)+ {+ hb_codepoint_t set_idx = c->depend_data->find_or_create_context_set (look_glyphs);+ if (unlikely (set_idx == HB_CODEPOINT_INVALID))+ return;+ context_glyphs.add (HB_DEPEND_CONTEXT_SET_FLAG | set_idx);+ }+ }++ /* Allocate context set and save/restore around edge creation */+ if (unlikely (context_glyphs.in_error ()))+ {+ c->depend_data->fail ();+ return;+ }+ hb_codepoint_t context_set_idx = context_glyphs.is_empty ()+ ? HB_CODEPOINT_INVALID+ : c->depend_data->find_or_create_context_set (context_glyphs);+ if (unlikely (!context_glyphs.is_empty () &&+ context_set_idx == HB_CODEPOINT_INVALID))+ return;++ hb_codepoint_t saved_context = c->depend_data->current_context_set_index;+ c->depend_data->current_context_set_index = context_set_idx;++ + hb_zip (this+coverage, substitute)+ | hb_filter (c->parent_active_glyphs (), hb_first)+ | hb_apply ([&] (const hb_codepoint_pair_t &_) { c->depend_data->add_gsub_lookup (_.first, c->lookup_index, _.second); })+ ;++ c->depend_data->current_context_set_index = saved_context;+ }+void closure (hb_closure_context_t *c) const{if (!intersects (c->glyphs)) return;diff --git a/thirdparty/harfbuzz/src/OT/Layout/GSUB/Sequence.hh b/thirdparty/harfbuzz/src/OT/Layout/GSUB/Sequence.hhindex 8edb0053b52..9c5dc864da8 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GSUB/Sequence.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GSUB/Sequence.hh@@ -28,6 +28,13 @@ struct Sequencevoid closure (hb_closure_context_t *c) const{ c->output->add_array (substitute.arrayZ, substitute.len); }+ void depend (hb_depend_context_t *c, hb_codepoint_t source) const+ {+ + hb_iter (substitute)+ | hb_apply ([&] (const hb_codepoint_t &target) { c->depend_data->add_gsub_lookup (source, c->lookup_index, target); })+ ;+ }+void collect_glyphs (hb_collect_glyphs_context_t *c) const{ c->output->add_array (substitute.arrayZ, substitute.len); }diff --git a/thirdparty/harfbuzz/src/OT/Layout/GSUB/SingleSubst.hh b/thirdparty/harfbuzz/src/OT/Layout/GSUB/SingleSubst.hhindex 7ffe3a68b8b..a7b35369fdb 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GSUB/SingleSubst.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GSUB/SingleSubst.hh@@ -30,11 +30,11 @@ struct SingleSubstif (unlikely (!c->may_dispatch (this, &u.format.v))) return c->no_dispatch_return_value ();TRACE_DISPATCH (this, u.format.v);switch (u.format.v) {- case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));- case 2: return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));+ case 1: hb_barrier (); return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));+ case 2: hb_barrier (); return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));#ifndef HB_NO_BEYOND_64K- case 3: return_trace (c->dispatch (u.format3, std::forward<Ts> (ds)...));- case 4: return_trace (c->dispatch (u.format4, std::forward<Ts> (ds)...));+ case 3: hb_barrier (); return_trace (c->dispatch (u.format3, std::forward<Ts> (ds)...));+ case 4: hb_barrier (); return_trace (c->dispatch (u.format4, std::forward<Ts> (ds)...));#endifdefault:return_trace (c->default_return_value ());}@@ -73,17 +73,17 @@ struct SingleSubstu.format.v = format;switch (u.format.v) {- case 1: return_trace (u.format1.serialize (c,+ case 1: hb_barrier (); return_trace (u.format1.serialize (c,+ glyphs| hb_map_retains_sorting (hb_first),delta));- case 2: return_trace (u.format2.serialize (c, glyphs));+ case 2: hb_barrier (); return_trace (u.format2.serialize (c, glyphs));#ifndef HB_NO_BEYOND_64K- case 3: return_trace (u.format3.serialize (c,+ case 3: hb_barrier (); return_trace (u.format3.serialize (c,+ glyphs| hb_map_retains_sorting (hb_first),delta));- case 4: return_trace (u.format4.serialize (c, glyphs));+ case 4: hb_barrier (); return_trace (u.format4.serialize (c, glyphs));#endifdefault:return_trace (false);}diff --git a/thirdparty/harfbuzz/src/OT/Layout/GSUB/SingleSubstFormat1.hh b/thirdparty/harfbuzz/src/OT/Layout/GSUB/SingleSubstFormat1.hhindex 1cd3f9d9cdf..bc18a8f32fa 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GSUB/SingleSubstFormat1.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GSUB/SingleSubstFormat1.hh@@ -45,6 +45,23 @@ struct SingleSubstFormat1_3bool may_have_non_1to1 () const{ return false; }+ void depend (hb_depend_context_t *c) const+ {+ hb_codepoint_t d = deltaGlyphID;+ hb_codepoint_t mask = get_mask ();+ unsigned num_glyphs = c->face->get_num_glyphs ();++ // Filter coverage by active glyphs (like closure does)+ hb_set_t intersection;+ (this+coverage).intersect_set (c->parent_active_glyphs (), intersection);++ + hb_iter (intersection)+ | hb_map ([&] (hb_codepoint_t _) { return hb_codepoint_pair_t (_, (_ + d) & mask); })+ | hb_filter ([num_glyphs] (const hb_codepoint_pair_t &_) { return _.second < num_glyphs; })+ | hb_apply ([&] (const hb_codepoint_pair_t &_) { c->depend_data->add_gsub_lookup(_.first, c->lookup_index, _.second); })+ ;+ }+void closure (hb_closure_context_t *c) const{hb_codepoint_t d = deltaGlyphID;@@ -109,7 +126,7 @@ struct SingleSubstFormat1_3return 0;}- if (alternate_count && *alternate_count)+ if (alternate_count && *alternate_count && alternate_glyphs){hb_codepoint_t d = deltaGlyphID;hb_codepoint_t mask = get_mask ();diff --git a/thirdparty/harfbuzz/src/OT/Layout/GSUB/SingleSubstFormat2.hh b/thirdparty/harfbuzz/src/OT/Layout/GSUB/SingleSubstFormat2.hhindex 4c98f05aeba..3836fb58517 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GSUB/SingleSubstFormat2.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GSUB/SingleSubstFormat2.hh@@ -34,6 +34,31 @@ struct SingleSubstFormat2_4bool may_have_non_1to1 () const{ return false; }+ void depend (hb_depend_context_t *c) const+ {+ auto &cov = this+coverage;+ auto &glyph_set = c->parent_active_glyphs ();++ // Filter by active glyphs like closure does+ if (substitute.len > glyph_set.get_population () * 4)+ {+ for (auto g : glyph_set)+ {+ unsigned i = cov.get_coverage (g);+ if (i == NOT_COVERED || i >= substitute.len)+ continue;+ c->depend_data->add_gsub_lookup (g, c->lookup_index, substitute.arrayZ[i]);+ }++ return;+ }++ + hb_zip (cov, substitute)+ | hb_filter (glyph_set, hb_first)+ | hb_apply ([&] (const hb_codepoint_pair_t &_) { c->depend_data->add_gsub_lookup (_.first, c->lookup_index, _.second); })+ ;+ }+void closure (hb_closure_context_t *c) const{auto &cov = this+coverage;@@ -89,7 +114,7 @@ struct SingleSubstFormat2_4return 0;}- if (alternate_count && *alternate_count)+ if (alternate_count && *alternate_count && alternate_glyphs){glyph_id = substitute[index];diff --git a/thirdparty/harfbuzz/src/OT/Layout/GSUB/SubstLookup.hh b/thirdparty/harfbuzz/src/OT/Layout/GSUB/SubstLookup.hhindex d49dcc0e0fd..ffa5e20bb4b 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GSUB/SubstLookup.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GSUB/SubstLookup.hh@@ -24,7 +24,7 @@ struct SubstLookup : Lookupbool is_reverse () const{unsigned int type = get_type ();- if (unlikely (type == SubTable::Extension))+ if (unlikely (type == SubTable::Extension) && hb_barrier ())return get_subtable (0).u.extension.is_reverse ();return lookup_type_is_reverse (type);}@@ -61,6 +61,12 @@ struct SubstLookup : Lookupreturn ret;}+ void depend (hb_depend_context_t *c) const+ {+ c->set_recurse_func (dispatch_depend_recurse_func);+ dispatch (c);+ }+hb_closure_lookups_context_t::return_t closure_lookups (hb_closure_lookups_context_t *c, unsigned this_index) const{if (c->is_lookup_visited (this_index))@@ -189,6 +195,7 @@ struct SubstLookup : Lookupstatic inline typename hb_closure_context_t::return_t closure_glyphs_recurse_func (hb_closure_context_t *c, unsigned lookup_index, hb_set_t *covered_seq_indices, unsigned seq_index, unsigned end_index);+static inline hb_closure_context_t::return_t dispatch_closure_recurse_func (hb_closure_context_t *c, unsigned lookup_index, hb_set_t *covered_seq_indices, unsigned seq_index, unsigned end_index){if (!c->should_visit_lookup (lookup_index))@@ -204,6 +211,13 @@ struct SubstLookup : Lookupreturn ret;}+ static inline hb_depend_context_t::return_t depend_glyphs_recurse_func (hb_depend_context_t *c, unsigned lookup_index, hb_bit_page_t *covered_seq_indices, unsigned seq_index, unsigned end_index);++ static inline hb_depend_context_t::return_t dispatch_depend_recurse_func (hb_depend_context_t *c, unsigned lookup_index, hb_bit_page_t *covered_seq_indices, unsigned seq_index, unsigned end_index)+ {+ return depend_glyphs_recurse_func (c, lookup_index, covered_seq_indices, seq_index, end_index);+ }+template <typename context_t, typename ...Ts>typename context_t::return_t dispatch (context_t *c, Ts&&... ds) const{ return Lookup::dispatch<SubTable> (c, std::forward<Ts> (ds)...); }diff --git a/thirdparty/harfbuzz/src/OT/Layout/GSUB/SubstLookupSubTable.hh b/thirdparty/harfbuzz/src/OT/Layout/GSUB/SubstLookupSubTable.hhindex a525fba0399..c36f0d7bf15 100644--- a/thirdparty/harfbuzz/src/OT/Layout/GSUB/SubstLookupSubTable.hh+++ b/thirdparty/harfbuzz/src/OT/Layout/GSUB/SubstLookupSubTable.hh@@ -50,14 +50,14 @@ struct SubstLookupSubTable{TRACE_DISPATCH (this, lookup_type);switch (lookup_type) {- case Single: return_trace (u.single.dispatch (c, std::forward<Ts> (ds)...));- case Multiple: return_trace (u.multiple.dispatch (c, std::forward<Ts> (ds)...));- case Alternate: return_trace (u.alternate.dispatch (c, std::forward<Ts> (ds)...));- case Ligature: return_trace (u.ligature.dispatch (c, std::forward<Ts> (ds)...));- case Context: return_trace (u.context.dispatch (c, std::forward<Ts> (ds)...));- case ChainContext: return_trace (u.chainContext.dispatch (c, std::forward<Ts> (ds)...));- case Extension: return_trace (u.extension.dispatch (c, std::forward<Ts> (ds)...));- case ReverseChainSingle: return_trace (u.reverseChainContextSingle.dispatch (c, std::forward<Ts> (ds)...));+ case Single: hb_barrier (); return_trace (u.single.dispatch (c, std::forward<Ts> (ds)...));+ case Multiple: hb_barrier (); return_trace (u.multiple.dispatch (c, std::forward<Ts> (ds)...));+ case Alternate: hb_barrier (); return_trace (u.alternate.dispatch (c, std::forward<Ts> (ds)...));+ case Ligature: hb_barrier (); return_trace (u.ligature.dispatch (c, std::forward<Ts> (ds)...));+ case Context: hb_barrier (); return_trace (u.context.dispatch (c, std::forward<Ts> (ds)...));+ case ChainContext: hb_barrier (); return_trace (u.chainContext.dispatch (c, std::forward<Ts> (ds)...));+ case Extension: hb_barrier (); return_trace (u.extension.dispatch (c, std::forward<Ts> (ds)...));+ case ReverseChainSingle: hb_barrier (); return_trace (u.reverseChainContextSingle.dispatch (c, std::forward<Ts> (ds)...));default: return_trace (c->default_return_value ());}}diff --git a/thirdparty/harfbuzz/src/OT/Var/VARC/VARC.cc b/thirdparty/harfbuzz/src/OT/Var/VARC/VARC.ccindex 7524686d30b..5b35a6a8d1e 100644--- a/thirdparty/harfbuzz/src/OT/Var/VARC/VARC.cc+++ b/thirdparty/harfbuzz/src/OT/Var/VARC/VARC.cc@@ -343,6 +343,11 @@ VARC::get_path_at (const hb_varc_context_t &c,{if (c.draw_session){+ /* Out of budget: draw nothing, but signal success so remaining+ * leaves are skipped instead of falling back per-glyph. */+ if (unlikely (c.budget_left <= 0)) return true;+ c.budget_left--;+hb_transform_t<> leaf_transform = transform;leaf_transform.x0 *= c.font->x_multf;leaf_transform.y0 *= c.font->y_multf;@@ -356,20 +361,23 @@ VARC::get_path_at (const hb_varc_context_t &c,hb_draw_session_t transformer_session {transformer_funcs, &context};hb_draw_session_t &shape_draw_session = leaf_transform.is_identity () ? *c.draw_session : transformer_session;- if (c.font->face->table.glyf->get_path_at (c.font, glyph, shape_draw_session, coords, c.scratch.glyf_scratch)) return true;+ if (c.font->face->table.glyf->get_path_at (c.font, glyph, shape_draw_session, coords, c.scratch.glyf_scratch, nullptr, &c.budget_left)) return true;#ifndef HB_NO_CFF- if (c.font->face->table.cff2->get_path_at (c.font, glyph, shape_draw_session, coords)) return true;- if (c.font->face->table.cff1->get_path (c.font, glyph, shape_draw_session)) return true; // Doesn't have variations+ if (c.font->face->table.cff2->get_path_at (c.font, glyph, shape_draw_session, coords, &c.budget_left)) return true;+ if (c.font->face->table.cff1->get_path (c.font, glyph, shape_draw_session, &c.budget_left)) return true; // Doesn't have variations#endifreturn false;}else if (c.extents){+ if (unlikely (c.budget_left <= 0)) return true;+ c.budget_left--;+hb_glyph_extents_t glyph_extents;- if (!c.font->face->table.glyf->get_extents_at (c.font, glyph, &glyph_extents, coords))+ if (!c.font->face->table.glyf->get_extents_at (c.font, glyph, &glyph_extents, coords, &c.budget_left))#ifndef HB_NO_CFF- if (!c.font->face->table.cff2->get_extents_at (c.font, glyph, &glyph_extents, coords))- if (!c.font->face->table.cff1->get_extents (c.font, glyph, &glyph_extents)) // Doesn't have variations+ if (!c.font->face->table.cff2->get_extents_at (c.font, glyph, &glyph_extents, coords, &c.budget_left))+ if (!c.font->face->table.cff1->get_extents (c.font, glyph, &glyph_extents, &c.budget_left)) // Doesn't have variations#endifreturn false;diff --git a/thirdparty/harfbuzz/src/OT/Var/VARC/VARC.hh b/thirdparty/harfbuzz/src/OT/Var/VARC/VARC.hhindex 719302c93e4..760c618e29b 100644--- a/thirdparty/harfbuzz/src/OT/Var/VARC/VARC.hh+++ b/thirdparty/harfbuzz/src/OT/Var/VARC/VARC.hh@@ -36,6 +36,10 @@ struct hb_varc_context_tmutable hb_decycler_t decycler;mutable signed edges_left;mutable signed depth_left;+ /* Work budget shared by all leaf glyphs loaded from glyf/CFF/CFF2,+ * so their per-glyph work limits cannot multiply with our own+ * composite-graph limits. */+ mutable int64_t budget_left;hb_varc_scratch_t &scratch;};@@ -120,6 +124,7 @@ struct VARChb_decycler_t {},HB_MAX_GRAPH_EDGE_COUNT,HB_MAX_NESTING_LEVEL,+ HB_VARC_MAX_WORK,scratch};return get_path_at (c, gid,@@ -138,6 +143,7 @@ struct VARChb_decycler_t {},HB_MAX_GRAPH_EDGE_COUNT,HB_MAX_NESTING_LEVEL,+ HB_VARC_MAX_WORK,scratch};return get_path_at (c, gid,diff --git a/thirdparty/harfbuzz/src/OT/glyf/glyf-helpers.hh b/thirdparty/harfbuzz/src/OT/glyf/glyf-helpers.hhindex f157bf00200..5dca10cbba1 100644--- a/thirdparty/harfbuzz/src/OT/glyf/glyf-helpers.hh+++ b/thirdparty/harfbuzz/src/OT/glyf/glyf-helpers.hh@@ -94,7 +94,7 @@ _add_loca_and_head (hb_subset_context_t *c,unsigned num_offsets = c->plan->num_output_glyphs () + 1;unsigned entry_size = use_short_loca ? 2 : 4;- char *loca_prime_data = (char *) hb_malloc (entry_size * num_offsets);+ char *loca_prime_data = (char *) hb_malloc2 (num_offsets, entry_size);if (unlikely (!loca_prime_data)) return false;diff --git a/thirdparty/harfbuzz/src/OT/glyf/glyf.hh b/thirdparty/harfbuzz/src/OT/glyf/glyf.hhindex a54587c8780..ce563977a52 100644--- a/thirdparty/harfbuzz/src/OT/glyf/glyf.hh+++ b/thirdparty/harfbuzz/src/OT/glyf/glyf.hh@@ -3,6 +3,7 @@#include "../../hb-open-type.hh"+#include "../../hb-depend-data.hh"#include "../../hb-ot-head-table.hh"#include "../../hb-ot-hmtx-table.hh"#include "../../hb-ot-var-gvar-table.hh"@@ -98,8 +99,11 @@ struct glyfreturn_trace (false);hb_vector_t<glyf_impl::SubsetGlyph> glyphs;- if (!_populate_subset_glyphs (c->plan, font, glyphs))+ /* SubsetGlyphs borrow bytes from this blob until they are serialized. */+ hb_blob_t *source_glyf = nullptr;+ if (!_populate_subset_glyphs (c->plan, font, glyphs, &source_glyf)){+ hb_blob_destroy (source_glyf);hb_font_destroy (font);return_trace (false);}@@ -130,6 +134,7 @@ struct glyfbool result = glyf_prime->serialize (c->serializer, hb_iter (glyphs), use_short_loca, c->plan);if (c->plan->normalized_coords && !c->plan->pinned_at_default)_free_compiled_subset_glyphs (glyphs);+ hb_blob_destroy (source_glyf);if (unlikely (!c->serializer->check_success (glyf_impl::_add_loca_and_head (c,padded_offsets.iter (),@@ -142,7 +147,8 @@ struct glyfbool_populate_subset_glyphs (const hb_subset_plan_t *plan,hb_font_t *font,- hb_vector_t<glyf_impl::SubsetGlyph>& glyphs /* OUT */) const;+ hb_vector_t<glyf_impl::SubsetGlyph>& glyphs /* OUT */,+ hb_blob_t **source_glyf /* OUT */) const;hb_font_t *_create_font_for_instancing (const hb_subset_plan_t *plan) const;@@ -216,6 +222,17 @@ struct glyf_accelerator_tbool has_data () const { return num_glyphs; }+ void depend (hb_depend_data_builder_t *builder) const+ {+ if (!has_data ()) return;+ for (hb_codepoint_t gid = 0; gid < get_num_glyphs (); gid++)+ {+ auto glyph = glyph_for_gid (gid);+ for (auto &item : glyph.get_composite_iterator ())+ builder->add_depend (gid, HB_OT_TAG_glyf, item.get_gid ());+ }+ }+protected:template<typename T>bool get_points (hb_font_t *font, hb_codepoint_t gid, T consumer,@@ -340,10 +357,12 @@ struct glyf_accelerator_treturn;}{- extents->x_bearing = roundf (min_x);- extents->width = roundf (max_x - extents->x_bearing);- extents->y_bearing = roundf (max_y);- extents->height = roundf (min_y - extents->y_bearing);+ double x_bearing = (double) roundf (min_x);+ double y_bearing = (double) roundf (max_y);+ extents->x_bearing = hb_clamp_to<hb_position_t> (x_bearing);+ extents->width = hb_clamp_to<hb_position_t> ((double) roundf (max_x) - x_bearing);+ extents->y_bearing = hb_clamp_to<hb_position_t> (y_bearing);+ extents->height = hb_clamp_to<hb_position_t> ((double) roundf (min_y) - y_bearing);if (scaled)font->scale_glyph_extents (extents);@@ -437,7 +456,8 @@ struct glyf_accelerator_tbool get_extents_at (hb_font_t *font,hb_codepoint_t gid,hb_glyph_extents_t *extents,- hb_array_t<const int> coords) const+ hb_array_t<const int> coords,+ int64_t *budget = nullptr) const{if (unlikely (gid >= num_glyphs)) return false;@@ -451,6 +471,7 @@ struct glyf_accelerator_tpoints_aggregator_t (font, extents, nullptr, true),coords,*scratch);+ if (budget) *budget -= scratch->all_points.length;release_scratch (scratch);return ret;}@@ -509,13 +530,16 @@ struct glyf_accelerator_tget_path_at (hb_font_t *font, hb_codepoint_t gid, hb_draw_session_t &draw_session,hb_array_t<const int> coords,hb_glyf_scratch_t &scratch,- hb_scalar_cache_t *gvar_cache = nullptr) const+ hb_scalar_cache_t *gvar_cache = nullptr,+ int64_t *budget = nullptr) const{if (!has_data ()) return false;- return get_points (font, gid, glyf_impl::path_builder_t (font, draw_session),- coords,- scratch,- gvar_cache);+ bool ret = get_points (font, gid, glyf_impl::path_builder_t (font, draw_session),+ coords,+ scratch,+ gvar_cache);+ if (budget) *budget -= scratch.all_points.length;+ return ret;}@@ -542,6 +566,10 @@ struct glyf_accelerator_t}}+ unsigned int get_num_glyphs () const { return num_glyphs; }+ hb_blob_t *reference_glyf_table () const+ { return hb_blob_reference (glyf_table.get_blob ()); }+#ifndef HB_NO_VARconst gvar_accelerator_t *gvar;#ifndef HB_NO_BEYOND_64K@@ -565,10 +593,12 @@ struct glyf_accelerator_tinline boolglyf::_populate_subset_glyphs (const hb_subset_plan_t *plan,hb_font_t *font,- hb_vector_t<glyf_impl::SubsetGlyph>& glyphs /* OUT */) const+ hb_vector_t<glyf_impl::SubsetGlyph>& glyphs /* OUT */,+ hb_blob_t **source_glyf /* OUT */) const{OT::glyf_accelerator_t glyf (plan->source);if (!glyphs.alloc_exact (plan->new_to_old_gid_list.length)) return false;+ *source_glyf = glyf.reference_glyf_table ();for (const auto &pair : plan->new_to_old_gid_list){@@ -614,6 +644,19 @@ glyf::_create_font_for_instancing (const hb_subset_plan_t *plan) consthb_font_t *font = hb_font_create (plan->source);if (unlikely (font == hb_font_get_empty ())) return nullptr;+#ifndef HB_NO_VAR+ if (plan->has_avar2)+ {+ /* Under avar2, instancing applies only to the self-contained pins,+ * whose constant final coordinates the plan holds in normalized_coords.+ * Setting user-space variations would run the full avar2 mapping and+ * bake contributions that remain live in the instance's variations. */+ hb_font_set_var_coords_normalized (font, plan->normalized_coords.arrayZ,+ plan->normalized_coords.length);+ return font;+ }+#endif+hb_vector_t<hb_variation_t> vars;if (unlikely (!vars.alloc (plan->user_axes_location.get_population (), true))){diff --git a/thirdparty/harfbuzz/src/graph/classdef-graph.hh b/thirdparty/harfbuzz/src/graph/classdef-graph.hhindex df06e00e725..fa604c90e04 100644--- a/thirdparty/harfbuzz/src/graph/classdef-graph.hh+++ b/thirdparty/harfbuzz/src/graph/classdef-graph.hh@@ -34,7 +34,7 @@ namespace graph {struct ClassDefFormat1 : public OT::ClassDefFormat1_3<SmallTypes>{- bool sanitize (graph_t::vertex_t& vertex) const+ bool sanitize (const graph_t::vertex_t& vertex) const{size_t vertex_len = vertex.obj.tail - vertex.obj.head;constexpr unsigned min_size = OT::ClassDefFormat1_3<SmallTypes>::min_size;@@ -46,7 +46,7 @@ struct ClassDefFormat1 : public OT::ClassDefFormat1_3<SmallTypes>struct ClassDefFormat2 : public OT::ClassDefFormat2_4<SmallTypes>{- bool sanitize (graph_t::vertex_t& vertex) const+ bool sanitize (const graph_t::vertex_t& vertex) const{size_t vertex_len = vertex.obj.tail - vertex.obj.head;constexpr unsigned min_size = OT::ClassDefFormat2_4<SmallTypes>::min_size;@@ -112,7 +112,7 @@ struct ClassDef : public OT::ClassDefreturn true;}- bool sanitize (graph_t::vertex_t& vertex) const+ bool sanitize (const graph_t::vertex_t& vertex) const{size_t vertex_len = vertex.obj.tail - vertex.obj.head;if (vertex_len < OT::ClassDef::min_size) return false;diff --git a/thirdparty/harfbuzz/src/graph/coverage-graph.hh b/thirdparty/harfbuzz/src/graph/coverage-graph.hhindex 5778ee9e1d3..457aab77156 100644--- a/thirdparty/harfbuzz/src/graph/coverage-graph.hh+++ b/thirdparty/harfbuzz/src/graph/coverage-graph.hh@@ -34,7 +34,7 @@ namespace graph {static bool sanitize (const OT::Layout::Common::CoverageFormat1_3<OT::Layout::SmallTypes>* thiz,- graph_t::vertex_t& vertex+ const graph_t::vertex_t& vertex) {size_t vertex_len = vertex.obj.tail - vertex.obj.head;constexpr unsigned min_size = OT::Layout::Common::CoverageFormat1_3<OT::Layout::SmallTypes>::min_size;@@ -45,7 +45,7 @@ static bool sanitize (static bool sanitize (const OT::Layout::Common::CoverageFormat2_4<OT::Layout::SmallTypes>* thiz,- graph_t::vertex_t& vertex+ const graph_t::vertex_t& vertex) {size_t vertex_len = vertex.obj.tail - vertex.obj.head;constexpr unsigned min_size = OT::Layout::Common::CoverageFormat2_4<OT::Layout::SmallTypes>::min_size;@@ -156,7 +156,7 @@ struct Coverage : public OT::Layout::Common::Coveragereturn true;}- bool sanitize (graph_t::vertex_t& vertex) const+ bool sanitize (const graph_t::vertex_t& vertex) const{size_t vertex_len = vertex.obj.tail - vertex.obj.head;if (vertex_len < OT::Layout::Common::Coverage::min_size) return false;diff --git a/thirdparty/harfbuzz/src/graph/graph.hh b/thirdparty/harfbuzz/src/graph/graph.hhindex 54df655aa09..d1030dbdb6b 100644--- a/thirdparty/harfbuzz/src/graph/graph.hh+++ b/thirdparty/harfbuzz/src/graph/graph.hh@@ -52,6 +52,7 @@ struct graph_tunsigned single_parent = (unsigned) -1;bool has_incoming_virtual_edges_ = false;hb_hashmap_t<unsigned, unsigned> parents;+ hb_set_t virtual_parents;public:auto parents_iter () const HB_AUTO_RETURN@@ -64,7 +65,7 @@ struct graph_tbool in_error () const{- return parents.in_error ();+ return parents.in_error () || virtual_parents.in_error ();}bool has_incoming_virtual_edges () const@@ -171,6 +172,7 @@ struct graph_thb_swap (a.space, b.space);hb_swap (a.single_parent, b.single_parent);hb_swap (a.parents, b.parents);+ hb_swap (a.virtual_parents, b.virtual_parents);hb_swap (a.incoming_edges_, b.incoming_edges_);hb_swap (a.has_incoming_virtual_edges_, b.has_incoming_virtual_edges_);hb_swap (a.start, b.start);@@ -193,7 +195,7 @@ struct graph_tbool is_shared () const{- return parents.get_population () > 1;+ return parents.get_population () > virtual_parents.get_population () + 1;}unsigned incoming_edges () const@@ -221,12 +223,15 @@ struct graph_thas_incoming_virtual_edges_ = false;single_parent = (unsigned) -1;parents.reset ();+ virtual_parents.reset ();}void add_parent (unsigned parent_index, bool is_virtual){assert (parent_index != (unsigned) -1);has_incoming_virtual_edges_ |= is_virtual;+ if (is_virtual)+ virtual_parents.add (parent_index);if (incoming_edges_ == 0){@@ -258,6 +263,7 @@ struct graph_t{single_parent = (unsigned) -1;incoming_edges_--;+ virtual_parents.reset ();return;}@@ -268,7 +274,10 @@ struct graph_tif (*v > 1)(*v)--;else+ {parents.del (parent_index);+ virtual_parents.del (parent_index);+ }if (incoming_edges_ == 1){@@ -295,37 +304,19 @@ struct graph_t}}- bool remap_parents (const hb_vector_t<unsigned>& id_map)- {- if (single_parent != (unsigned) -1)- {- assert (single_parent < id_map.length);- single_parent = id_map[single_parent];- return true;- }-- hb_hashmap_t<unsigned, unsigned> new_parents;- new_parents.alloc (parents.get_population ());- for (auto _ : parents)- {- assert (_.first < id_map.length);- assert (!new_parents.has (id_map[_.first]));- new_parents.set (id_map[_.first], _.second);- }-- if (parents.in_error() || new_parents.in_error ())- return false;-- parents = std::move (new_parents);- return true;- }-void remap_parent (unsigned old_index, unsigned new_index){if (single_parent != (unsigned) -1){if (single_parent == old_index)+ {single_parent = new_index;+ if (virtual_parents.has (old_index))+ {+ virtual_parents.del (old_index);+ virtual_parents.add (new_index);+ }+ }return;}@@ -343,6 +334,12 @@ struct graph_tparents.reset ();}}++ if (virtual_parents.has (old_index))+ {+ virtual_parents.del (old_index);+ virtual_parents.add (new_index);+ }}bool is_leaf () const@@ -437,19 +434,29 @@ struct graph_t}};- template <typename T>+ enum vertex_mutability_t+ {+ Immutable,+ Mutable+ };++ template <typename T, vertex_mutability_t mutability = Mutable>struct vertex_and_table_t{vertex_and_table_t () : index (0), vertex (nullptr), table (nullptr){}+ template <vertex_mutability_t other_mutability>+ vertex_and_table_t (const vertex_and_table_t<T, other_mutability>& o)+ : index (o.index), vertex (o.vertex), table (o.table)+ {}+unsigned index;- vertex_t* vertex;- T* table;+ typename std::conditional<mutability == Immutable, const vertex_t*, vertex_t*>::type vertex;+ typename std::conditional<mutability == Immutable, const T*, T*>::type table;- operator bool () {- return table && vertex;- }+ operator bool () const+ { return table && vertex; }};/*@@ -467,6 +474,15 @@ struct graph_tsuccessful (true),buffers (){+ if (objects.length > HB_REPACKER_MAX_VERTICES)+ {+ DEBUG_MSG (SUBSET_REPACK, nullptr,+ "constructing graph: num of objects %u exceeds HB_REPACKER_MAX_VERTICES.",+ objects.length);+ check_success (false);+ return;+ }+num_roots_for_space_.push (1);bool removed_nil = false;vertices_.alloc (objects.length);@@ -712,32 +728,32 @@ struct graph_t}template <typename T, typename ...Ts>- vertex_and_table_t<T> as_table (unsigned parent, const void* offset, Ts... ds)+ const vertex_and_table_t<T, Immutable> as_table (unsigned parent, const void* offset, Ts... ds){return as_table_from_index<T> (index_for_offset (parent, offset), std::forward<Ts>(ds)...);}template <typename T, typename ...Ts>- vertex_and_table_t<T> as_mutable_table (unsigned parent, const void* offset, Ts... ds)+ vertex_and_table_t<T, Mutable> as_mutable_table (unsigned parent, const void* offset, Ts... ds){- return as_table_from_index<T> (mutable_index_for_offset (parent, offset), std::forward<Ts>(ds)...);+ return as_table_from_index<T, Mutable> (mutable_index_for_offset (parent, offset), std::forward<Ts>(ds)...);}- template <typename T, typename ...Ts>- vertex_and_table_t<T> as_table_from_index (unsigned index, Ts... ds)+ template <typename T, vertex_mutability_t mutability = Mutable, typename ...Ts>+ vertex_and_table_t<T, mutability> as_table_from_index (unsigned index, Ts... ds){if (index >= vertices_.length)- return vertex_and_table_t<T> ();+ return vertex_and_table_t<T, mutability> ();- vertex_and_table_t<T> r;- r.vertex = &vertices_[index];- r.table = (T*) r.vertex->obj.head;+ vertex_and_table_t<T, mutability> r;+ r.vertex = (typename std::conditional<mutability == Immutable, const vertex_t*, vertex_t*>::type) &vertices_[index];+ r.table = (typename std::conditional<mutability == Immutable, const T*, T*>::type) r.vertex->obj.head;r.index = index;if (!r.table)- return vertex_and_table_t<T> ();+ return vertex_and_table_t<T, mutability> ();if (!r.table->sanitize (*(r.vertex), std::forward<Ts>(ds)...))- return vertex_and_table_t<T> ();+ return vertex_and_table_t<T, mutability> ();return r;}@@ -773,7 +789,7 @@ struct graph_tfor (unsigned p : child.parents_iter ()){if (p != node_idx) {- return duplicate (node_idx, child_idx);+ return duplicate (node_idx, child_idx, true);}}@@ -816,6 +832,9 @@ struct graph_tunsigned next_space = this->next_space ();if (next_space >= HB_REPACKER_MAX_SPACES){+ DEBUG_MSG (SUBSET_REPACK, nullptr,+ "num of spaces %u exceeds HB_REPACKER_MAX_SPACES.",+ next_space);check_success (false);break;}@@ -909,41 +928,123 @@ struct graph_treturn true;}- void find_subgraph (unsigned node_idx, hb_map_t& subgraph)+ // BFS graph traversal starting at start_idx.+ //+ // The visit_edge function will be called once for the root node and then for each traversed edge+ // with the following signature:+ //+ // bool VisitEdgeFunc(unsigned parent, const link_t* link, unsigned child, unsigned depth)+ //+ // Where a return value of false signals that traversal should not continue into child's outgoing+ // edges. parent/child are the vertex indices. depth starts at 0 for the root node.+ // link will be null when called for entering the root node at the start of the traversal.+ //+ // This traversal does not use a visited set internally, it is the responsibility of visit_edge+ // to track and filter visited nodes if required for the particular traversal.+ template <typename VisitEdgeFunc>+ void traverse_directed_bfs (unsigned start_idx, VisitEdgeFunc&& visit_edge){- for (const auto& link : vertices_[node_idx].obj.all_links ())+ if (unlikely (!check_success(start_idx < vertices_.length)))+ {+ DEBUG_MSG (SUBSET_REPACK, nullptr,+ "traverse_directed_bfs: unexpected start_idx out of bounds.");+ return;+ }++ // For performance we want to avoid allocating extra memory. So use the ordering_scratch_+ // buffer to implement a queue for BFS.+ if (unlikely (!check_success (ordering_scratch_.resize (vertices_.length))))+ return;++ if (!visit_edge (HB_CODEPOINT_INVALID, nullptr, start_idx, 0))+ return;++ unsigned head = 0;+ unsigned tail = 0;+ auto& queue = ordering_scratch_;+ queue[tail++] = start_idx;++ unsigned depth = 0;+ while (head < tail){- hb_codepoint_t *v;- if (subgraph.has (link.objidx, &v))+ unsigned level_end = tail;+ while (head < level_end){- (*v)++;- continue;+ unsigned node_idx = queue[head++];+ const auto& v = vertices_[node_idx];++ unsigned num_real = v.obj.real_links.length;+ unsigned total_links = num_real + v.obj.virtual_links.length;++ for (unsigned i = 0; i < total_links; i++)+ {+ // vertices_ may have re-alloc'd inside an op() call, so reassign the v ref.+ const auto& v = vertices_[node_idx];+ const auto& link = (i < num_real)+ ? v.obj.real_links[i]+ : v.obj.virtual_links[i - num_real];+ unsigned child_idx = link.objidx;++ if (!visit_edge (node_idx, &link, child_idx, depth + 1))+ continue;++ if (unlikely (!check_success (tail < queue.length)))+ return;++ queue[tail++] = child_idx;+ }}- subgraph.set (link.objidx, 1);- find_subgraph (link.objidx, subgraph);+ depth++;}}+ void find_subgraph (unsigned node_idx, hb_map_t& subgraph)+ {+ traverse_directed_bfs (node_idx, [&] (+ unsigned parent,+ const hb_serialize_context_t::object_t::link_t* link,+ unsigned child,+ unsigned depth) {+ if (depth == 0) return true;+ hb_codepoint_t *count;+ if (subgraph.has (child, &count))+ {+ (*count)++;+ return false;+ }+ subgraph.set (child, 1);+ return true;+ });+ }+void find_subgraph (unsigned node_idx, hb_set_t& subgraph){- if (subgraph.has (node_idx)) return;- subgraph.add (node_idx);- for (const auto& link : vertices_[node_idx].obj.all_links ())- find_subgraph (link.objidx, subgraph);+ traverse_directed_bfs (node_idx, [&] (+ unsigned parent,+ const hb_serialize_context_t::object_t::link_t* link,+ unsigned child,+ unsigned depth) {+ if (subgraph.has (child)) return false;+ subgraph.add (child);+ return true;+ });}size_t find_subgraph_size (unsigned node_idx, hb_set_t& subgraph, unsigned max_depth = -1){- if (subgraph.has (node_idx)) return 0;- subgraph.add (node_idx);-- const auto& o = vertices_[node_idx].obj;- size_t size = o.tail - o.head;- if (max_depth == 0)- return size;-- for (const auto& link : o.all_links ())- size += find_subgraph_size (link.objidx, subgraph, max_depth - 1);+ size_t size = 0;+ traverse_directed_bfs (node_idx, [&] (+ unsigned parent,+ const hb_serialize_context_t::object_t::link_t* link,+ unsigned child,+ unsigned depth) {+ if (subgraph.has (child)) return false;+ subgraph.add (child);++ const auto& o = vertices_[child].obj;+ size += o.tail - o.head;+ return depth < max_depth;+ });return size;}@@ -953,14 +1054,30 @@ struct graph_t*/void find_32bit_roots (unsigned node_idx, hb_set_t& found){- for (const auto& link : vertices_[node_idx].obj.all_links ())- {- if (!link.is_signed && link.width == 4) {- found.add (link.objidx);- continue;+ // Note: this specifically requires a BFS based traversal to ensure we don't recurse through+ // a node that is accessible via both 32bit and non-32 bit links.+ hb_set_t visited;+ traverse_directed_bfs (node_idx, [&] (+ unsigned parent,+ const hb_serialize_context_t::object_t::link_t* link,+ unsigned child,+ unsigned _) {++ if (link && found.has(parent))+ // Don't traverse from something that's already marked as a root.+ return false;++ if (link && !link->is_signed && link->width == 4)+ {+ found.add (link->objidx);+ visited.add (link->objidx);+ return false;}- find_32bit_roots (link.objidx, found);- }++ if (visited.has (child)) return false;+ visited.add (child);+ return true;+ });}/*@@ -1049,26 +1166,29 @@ struct graph_t*/void duplicate_subgraph (unsigned node_idx, hb_map_t& index_map){- if (index_map.has (node_idx))- return;-- unsigned clone_idx = duplicate (node_idx);- if (!check_success (clone_idx != (unsigned) -1))- return;-- index_map.set (node_idx, clone_idx);- for (const auto& l : object (node_idx).all_links ()) {- duplicate_subgraph (l.objidx, index_map);- }+ traverse_directed_bfs (node_idx, [&] (+ unsigned parent,+ const hb_serialize_context_t::object_t::link_t* link,+ unsigned child,+ unsigned _) {+ if (index_map.has (child)) return false;+ unsigned clone_idx = duplicate (child);+ if (!check_success (clone_idx != (unsigned) -1)) return false;+ index_map.set (child, clone_idx);+ return true;+ });}/** Creates a copy of node_idx and returns it's new index.*/- unsigned duplicate (unsigned node_idx)+ unsigned duplicate (unsigned node_idx, bool copy_table = false){if (vertices_.length >= HB_REPACKER_MAX_VERTICES){+ DEBUG_MSG (SUBSET_REPACK, nullptr,+ "duplicating node: num of vertices %u exceeds HB_REPACKER_MAX_VERTICES.",+ vertices_.length);check_success (false);return -1;}@@ -1085,8 +1205,24 @@ struct graph_treturn -1;}- clone->obj.head = child.obj.head;- clone->obj.tail = child.obj.tail;+ unsigned table_size = child.obj.tail - child.obj.head;+ if (copy_table && table_size)+ {+ char* buffer = (char*) hb_malloc (table_size);+ if (!check_success (buffer && add_buffer (buffer)))+ {+ hb_free (buffer);+ return -1;+ }+ hb_memcpy (buffer, child.obj.head, table_size);+ clone->obj.head = buffer;+ clone->obj.tail = buffer + table_size;+ }+ else+ {+ clone->obj.head = child.obj.head;+ clone->obj.tail = child.obj.tail;+ }clone->distance = child.distance;clone->space = child.space;clone->reset_parents ();@@ -1118,7 +1254,7 @@ struct graph_t* If the child_idx only has incoming edges from parent_idx,* duplication isn't possible and this will return -1.*/- unsigned duplicate (unsigned parent_idx, unsigned child_idx)+ unsigned duplicate (unsigned parent_idx, unsigned child_idx, bool copy_table = false){update_parents ();@@ -1142,7 +1278,7 @@ struct graph_tDEBUG_MSG (SUBSET_REPACK, nullptr, " Duplicating %u => %u",parent_idx, child_idx);- unsigned clone_idx = duplicate (child_idx);+ unsigned clone_idx = duplicate (child_idx, copy_table);if (clone_idx == (unsigned) -1) return -1;// duplicate shifts the root node idx, so if parent_idx was root update it.if (parent_idx == clone_idx) parent_idx++;@@ -1234,6 +1370,9 @@ struct graph_t{if (vertices_.length >= HB_REPACKER_MAX_VERTICES){+ DEBUG_MSG (SUBSET_REPACK, nullptr,+ "creating new node: num of vertices %u exceeds HB_REPACKER_MAX_VERTICES.",+ vertices_.length);check_success (false);return -1;}@@ -1403,6 +1542,9 @@ struct graph_t{if (num_roots_for_space_.length >= HB_REPACKER_MAX_SPACES){+ DEBUG_MSG (SUBSET_REPACK, nullptr,+ "move_to_new_space: num of spaces %u exceeds HB_REPACKER_MAX_SPACES.",+ num_roots_for_space_.length);check_success (false);return;}@@ -1656,22 +1798,53 @@ struct graph_t{if (unlikely (!check_success (!visited.in_error ()))) return;if (visited.has (start_idx)) return;- visited.add (start_idx);-- if (targets.has (start_idx))+ if (unlikely (!check_success(start_idx < vertices_.length))){- targets.del (start_idx);- connected.add (start_idx);+ DEBUG_MSG (SUBSET_REPACK, nullptr,+ "find_connected_nodes: unexpected start_idx out of bounds.");+ return;}- const auto& v = vertices_[start_idx];+ // For performance we want to avoid allocating extra memory. So use the ordering_scratch_+ // buffer to implement a stack for DFS.+ if (unlikely (!check_success (ordering_scratch_.resize (vertices_.length)))) return;- // Graph is treated as undirected so search children and parents of start_idx- for (const auto& l : v.obj.all_links ())- find_connected_nodes (l.objidx, targets, visited, connected);+ auto& stack = ordering_scratch_;+ unsigned stack_len = 0;- for (unsigned p : v.parents_iter ())- find_connected_nodes (p, targets, visited, connected);+ auto handle_node = [&] (unsigned node_idx) {+ visited.add (node_idx);+ if (targets.has (node_idx)) {+ targets.del (node_idx);+ connected.add (node_idx);+ }++ if (unlikely (!check_success (stack_len < stack.length))) return false;+ stack[stack_len++] = node_idx;+ return true;+ };++ if (!handle_node (start_idx)) return;++ while (stack_len > 0)+ {+ unsigned node_idx = stack[--stack_len];+ const auto& v = vertices_[node_idx];++ // Graph is treated as undirected so search children and parents of node_idx+ for (const auto& l : v.obj.all_links ())+ {+ unsigned child_idx = l.objidx;+ if (visited.has (child_idx)) continue;+ if (!handle_node (child_idx)) return;+ }++ for (unsigned parent_idx : v.parents_iter ())+ {+ if (visited.has (parent_idx)) continue;+ if (!handle_node (parent_idx)) return;+ }+ }}public:diff --git a/thirdparty/harfbuzz/src/graph/gsubgpos-graph.hh b/thirdparty/harfbuzz/src/graph/gsubgpos-graph.hhindex 73f4b15660f..dd6ed1bddce 100644--- a/thirdparty/harfbuzz/src/graph/gsubgpos-graph.hh+++ b/thirdparty/harfbuzz/src/graph/gsubgpos-graph.hh@@ -50,7 +50,7 @@ struct ExtensionFormat1 : public OT::ExtensionFormat1<T>this->extensionOffset = 0;}- bool sanitize (graph_t::vertex_t& vertex) const+ bool sanitize (const graph_t::vertex_t& vertex) const{size_t vertex_len = vertex.obj.tail - vertex.obj.head;return vertex_len >= OT::ExtensionFormat1<T>::static_size;@@ -74,7 +74,7 @@ struct Lookup : public OT::Lookupreturn subTable.len;}- bool sanitize (graph_t::vertex_t& vertex) const+ bool sanitize (const graph_t::vertex_t& vertex) const{size_t vertex_len = vertex.obj.tail - vertex.obj.head;if (vertex_len < OT::Lookup::min_size) return false;@@ -414,9 +414,9 @@ struct GSTAR : public OT::GSUBGPOSconst void* get_lookup_list_field_offset () const{switch (u.version.major) {- case 1: return u.version1.get_lookup_list_offset ();+ case 1: hb_barrier (); return u.version1.get_lookup_list_offset ();#ifndef HB_NO_BEYOND_64K- case 2: return u.version2.get_lookup_list_offset ();+ case 2: hb_barrier (); return u.version2.get_lookup_list_offset ();#endifdefault: return 0;}diff --git a/thirdparty/harfbuzz/src/graph/ligature-graph.hh b/thirdparty/harfbuzz/src/graph/ligature-graph.hhindex 4ef78e53ecf..44f777be674 100644--- a/thirdparty/harfbuzz/src/graph/ligature-graph.hh+++ b/thirdparty/harfbuzz/src/graph/ligature-graph.hh@@ -1,3 +1,4 @@+/** Copyright © 2025 Google, Inc.*@@ -39,7 +40,7 @@ namespace graph {struct LigatureSet : public OT::Layout::GSUB_impl::LigatureSet<SmallTypes>{- bool sanitize (graph_t::vertex_t& vertex) const+ bool sanitize (const graph_t::vertex_t& vertex) const{size_t vertex_len = vertex.obj.tail - vertex.obj.head;if (vertex_len < OT::Layout::GSUB_impl::LigatureSet<SmallTypes>::min_size) return false;@@ -55,7 +56,7 @@ struct LigatureSet : public OT::Layout::GSUB_impl::LigatureSet<SmallTypes>struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1_2<SmallTypes>{- bool sanitize (graph_t::vertex_t& vertex) const+ bool sanitize (const graph_t::vertex_t& vertex) const{size_t vertex_len = vertex.obj.tail - vertex.obj.head;unsigned min_size = OT::Layout::GSUB_impl::LigatureSubstFormat1_2<SmallTypes>::min_size;@@ -70,6 +71,9 @@ struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1unsigned this_index){auto split_points = compute_split_points(c, this_index);+ if (!split_points)+ return hb_vector_t<unsigned> ();+split_context_t split_context {c,this,@@ -104,7 +108,8 @@ struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1return result;}- hb_vector_t<unsigned> ligature_index_to_object_id(const graph_t::vertex_and_table_t<LigatureSet>& liga_set) const {+ template <graph_t::vertex_mutability_t mutability>+ hb_vector_t<unsigned> ligature_index_to_object_id(const graph_t::vertex_and_table_t<LigatureSet, mutability>& liga_set) const {hb_vector_t<unsigned> map;map.resize_exact(liga_set.table->ligature.len);if (map.in_error()) return map;@@ -317,12 +322,12 @@ struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1continue;}- auto liga_set_index = c.graph.index_for_offset(this_index, &ligatureSet[i]);- auto liga_set = c.graph.as_table<LigatureSet>(this_index, &ligatureSet[i]);+ auto liga_set = c.graph.as_mutable_table<LigatureSet>(this_index, &ligatureSet[i]);if (!liga_set.table) {return -1;}+ unsigned liga_set_index = liga_set.index;// Bounds may need to be adjusted if some ligas have been previously removed.hb_pair_t<unsigned, unsigned> liga_bounds = current_liga_set_bounds(c, liga_set_index, liga_set.vertex->obj);current_start = hb_max(count + liga_bounds.first, current_start);@@ -403,7 +408,7 @@ struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1unsigned new_liga_set_count = 0;for (unsigned i = 0; i < liga_counts.length; i++){- auto liga_set = c.graph.as_table<LigatureSet>(this_index, &ligatureSet[i]);+ auto liga_set = c.graph.as_mutable_table<LigatureSet>(this_index, &ligatureSet[i]);if (!liga_set.table) {return false;}@@ -480,6 +485,7 @@ struct LigatureSubst : public OT::Layout::GSUB_impl::LigatureSubst{switch (u.format.v) {case 1:+ hb_barrier ();return ((LigatureSubstFormat1*)(&u.format1))->split_subtables (c, this_index);#ifndef HB_NO_BEYOND_64Kcase 2: HB_FALLTHROUGH;@@ -490,7 +496,7 @@ struct LigatureSubst : public OT::Layout::GSUB_impl::LigatureSubst}}- bool sanitize (graph_t::vertex_t& vertex) const+ bool sanitize (const graph_t::vertex_t& vertex) const{size_t vertex_len = vertex.obj.tail - vertex.obj.head;if (vertex_len < u.format.v.get_size ()) return false;@@ -498,6 +504,7 @@ struct LigatureSubst : public OT::Layout::GSUB_impl::LigatureSubstswitch (u.format.v) {case 1:+ hb_barrier ();return ((LigatureSubstFormat1*)(&u.format1))->sanitize (vertex);#ifndef HB_NO_BEYOND_64Kcase 2: HB_FALLTHROUGH;diff --git a/thirdparty/harfbuzz/src/graph/markbasepos-graph.hh b/thirdparty/harfbuzz/src/graph/markbasepos-graph.hhindex a653f402ab1..e476a90b891 100644--- a/thirdparty/harfbuzz/src/graph/markbasepos-graph.hh+++ b/thirdparty/harfbuzz/src/graph/markbasepos-graph.hh@@ -36,7 +36,7 @@ namespace graph {struct AnchorMatrix : public OT::Layout::GPOS_impl::AnchorMatrix{- bool sanitize (graph_t::vertex_t& vertex, unsigned class_count) const+ bool sanitize (const graph_t::vertex_t& vertex, unsigned class_count) const{size_t vertex_len = vertex.obj.tail - vertex.obj.head;if (vertex_len < AnchorMatrix::min_size) return false;@@ -124,7 +124,7 @@ struct AnchorMatrix : public OT::Layout::GPOS_impl::AnchorMatrixstruct MarkArray : public OT::Layout::GPOS_impl::MarkArray{- bool sanitize (graph_t::vertex_t& vertex) const+ bool sanitize (const graph_t::vertex_t& vertex) const{size_t vertex_len = vertex.obj.tail - vertex.obj.head;unsigned min_size = MarkArray::min_size;@@ -205,7 +205,7 @@ struct MarkArray : public OT::Layout::GPOS_impl::MarkArraystruct MarkBasePosFormat1 : public OT::Layout::GPOS_impl::MarkBasePosFormat1_2<SmallTypes>{- bool sanitize (graph_t::vertex_t& vertex) const+ bool sanitize (const graph_t::vertex_t& vertex) const{size_t vertex_len = vertex.obj.tail - vertex.obj.head;return vertex_len >= MarkBasePosFormat1::static_size;@@ -448,7 +448,7 @@ struct MarkBasePosFormat1 : public OT::Layout::GPOS_impl::MarkBasePosFormat1_2<Sreturn -1;auto mark_array =- graph.as_table <MarkArray> (sc.this_index, &markArray);+ graph.as_mutable_table <MarkArray> (sc.this_index, &markArray);if (!mark_array) return -1;unsigned new_mark_array =mark_array.table->clone (sc.c,@@ -460,7 +460,7 @@ struct MarkBasePosFormat1 : public OT::Layout::GPOS_impl::MarkBasePosFormat1_2<Sunsigned class_count = classCount;auto base_array =- graph.as_table<AnchorMatrix> (sc.this_index, &baseArray, class_count);+ graph.as_mutable_table<AnchorMatrix> (sc.this_index, &baseArray, class_count);if (!base_array) return -1;unsigned new_base_array =base_array.table->clone (sc.c,@@ -480,6 +480,7 @@ struct MarkBasePos : public OT::Layout::GPOS_impl::MarkBasePos{switch (u.format.v) {case 1:+ hb_barrier ();return ((MarkBasePosFormat1*)(&u.format1))->split_subtables (c, this_index);#ifndef HB_NO_BEYOND_64Kcase 2: HB_FALLTHROUGH;@@ -490,7 +491,7 @@ struct MarkBasePos : public OT::Layout::GPOS_impl::MarkBasePos}}- bool sanitize (graph_t::vertex_t& vertex) const+ bool sanitize (const graph_t::vertex_t& vertex) const{size_t vertex_len = vertex.obj.tail - vertex.obj.head;if (vertex_len < u.format.v.get_size ()) return false;@@ -498,6 +499,7 @@ struct MarkBasePos : public OT::Layout::GPOS_impl::MarkBasePosswitch (u.format.v) {case 1:+ hb_barrier ();return ((MarkBasePosFormat1*)(&u.format1))->sanitize (vertex);#ifndef HB_NO_BEYOND_64Kcase 2: HB_FALLTHROUGH;diff --git a/thirdparty/harfbuzz/src/graph/pairpos-graph.hh b/thirdparty/harfbuzz/src/graph/pairpos-graph.hhindex 7c3b048195d..65b17001768 100644--- a/thirdparty/harfbuzz/src/graph/pairpos-graph.hh+++ b/thirdparty/harfbuzz/src/graph/pairpos-graph.hh@@ -37,7 +37,7 @@ namespace graph {struct PairPosFormat1 : public OT::Layout::GPOS_impl::PairPosFormat1_3<SmallTypes>{- bool sanitize (graph_t::vertex_t& vertex) const+ bool sanitize (const graph_t::vertex_t& vertex) const{size_t vertex_len = vertex.obj.tail - vertex.obj.head;unsigned min_size = OT::Layout::GPOS_impl::PairPosFormat1_3<SmallTypes>::min_size;@@ -193,7 +193,7 @@ struct PairPosFormat1 : public OT::Layout::GPOS_impl::PairPosFormat1_3<SmallTypestruct PairPosFormat2 : public OT::Layout::GPOS_impl::PairPosFormat2_4<SmallTypes>{- bool sanitize (graph_t::vertex_t& vertex) const+ bool sanitize (const graph_t::vertex_t& vertex) const{size_t vertex_len = vertex.table_size ();unsigned min_size = OT::Layout::GPOS_impl::PairPosFormat2_4<SmallTypes>::min_size;@@ -608,8 +608,10 @@ struct PairPos : public OT::Layout::GPOS_impl::PairPos{switch (u.format.v) {case 1:+ hb_barrier ();return ((PairPosFormat1*)(&u.format1))->split_subtables (c, this_index);case 2:+ hb_barrier ();return ((PairPosFormat2*)(&u.format2))->split_subtables (c, this_index);#ifndef HB_NO_BEYOND_64Kcase 3: HB_FALLTHROUGH;@@ -621,7 +623,7 @@ struct PairPos : public OT::Layout::GPOS_impl::PairPos}}- bool sanitize (graph_t::vertex_t& vertex) const+ bool sanitize (const graph_t::vertex_t& vertex) const{size_t vertex_len = vertex.obj.tail - vertex.obj.head;if (vertex_len < u.format.v.get_size ()) return false;@@ -629,8 +631,10 @@ struct PairPos : public OT::Layout::GPOS_impl::PairPosswitch (u.format.v) {case 1:+ hb_barrier ();return ((PairPosFormat1*)(&u.format1))->sanitize (vertex);case 2:+ hb_barrier ();return ((PairPosFormat2*)(&u.format2))->sanitize (vertex);#ifndef HB_NO_BEYOND_64Kcase 3: HB_FALLTHROUGH;diff --git a/thirdparty/harfbuzz/src/graph/serialize.hh b/thirdparty/harfbuzz/src/graph/serialize.hhindex 4f89f1011d8..4ad4b0b068c 100644--- a/thirdparty/harfbuzz/src/graph/serialize.hh+++ b/thirdparty/harfbuzz/src/graph/serialize.hh@@ -176,7 +176,12 @@ serialize_link_of_type (const hb_serialize_context_t::object_t::link_t& link,const hb_vector_t<unsigned>& id_map,hb_serialize_context_t* c){- assert(link.position + link.width <= size);+ // A link must never write outside the bounds of its parent object.+ if (unlikely (link.position + link.width > size))+ {+ c->err (HB_SERIALIZE_ERROR_OTHER);+ return;+ }OT::Offset<O>* offset = reinterpret_cast<OT::Offset<O>*> (head + link.position);*offset = 0;diff --git a/thirdparty/harfbuzz/src/hb-aat-layout-bsln-table.hh b/thirdparty/harfbuzz/src/hb-aat-layout-bsln-table.hhindex 8e42fab2e04..02e5f94395f 100644--- a/thirdparty/harfbuzz/src/hb-aat-layout-bsln-table.hh+++ b/thirdparty/harfbuzz/src/hb-aat-layout-bsln-table.hh@@ -127,10 +127,10 @@ struct bslnswitch (format){- case 0: return_trace (parts.format0.sanitize (c));- case 1: return_trace (parts.format1.sanitize (c));- case 2: return_trace (parts.format2.sanitize (c));- case 3: return_trace (parts.format3.sanitize (c));+ case 0: hb_barrier (); return_trace (parts.format0.sanitize (c));+ case 1: hb_barrier (); return_trace (parts.format1.sanitize (c));+ case 2: hb_barrier (); return_trace (parts.format2.sanitize (c));+ case 3: hb_barrier (); return_trace (parts.format3.sanitize (c));default:return_trace (true);}}diff --git a/thirdparty/harfbuzz/src/hb-aat-layout-common.hh b/thirdparty/harfbuzz/src/hb-aat-layout-common.hhindex cec42c54f01..9bba4032360 100644--- a/thirdparty/harfbuzz/src/hb-aat-layout-common.hh+++ b/thirdparty/harfbuzz/src/hb-aat-layout-common.hh@@ -49,6 +49,17 @@ struct ankr;using hb_aat_class_cache_t = hb_ot_layout_mapping_cache_t;+/* The state-machine subtables' transition functions are called once per+ * transition from the drive loop, but are big enough that the compiler+ * declines to inline them, leaving a call in the hottest loop of AAT+ * shaping. Forcing them inline is worth 3-10% instructions on+ * morx/kerx-heavy fonts, for about 16KB of code. */+#ifndef HB_OPTIMIZE_SIZE+#define HB_AAT_TRANSITION_INLINE HB_ALWAYS_INLINE+#else+#define HB_AAT_TRANSITION_INLINE+#endif+struct hb_aat_scratch_t{hb_aat_scratch_t () = default;@@ -182,20 +193,26 @@ struct hb_aat_apply_context_t :buffer_glyph_set->add_array (glyphs, count);for (unsigned int i = 0; i < count; i++){+ bool at_end_of_text = buffer->idx == buffer->len;+ if (at_end_of_text)+ if (unlikely (!buffer->output_glyph (glyphs[i]))) return false;++ hb_glyph_info_t &info = at_end_of_text ? buffer->prev () : buffer->cur ();if (glyphs[i] == DELETED_GLYPH){buffer->scratch_flags |= HB_BUFFER_SCRATCH_FLAG_AAT_HAS_DELETED;- _hb_glyph_info_set_aat_deleted (&buffer->cur());+ _hb_glyph_info_set_aat_deleted (&info);}else{#ifndef HB_NO_OT_LAYOUTif (has_glyph_classes)- _hb_glyph_info_set_glyph_props (&buffer->cur(),+ _hb_glyph_info_set_glyph_props (&info,gdef.get_glyph_props (glyphs[i]));#endif}- if (unlikely (!buffer->output_glyph (glyphs[i]))) return false;+ if (!at_end_of_text)+ if (unlikely (!buffer->output_glyph (glyphs[i]))) return false;}return true;}@@ -228,6 +245,11 @@ struct hb_aat_apply_context_t :void replace_glyph_inplace (unsigned i, hb_codepoint_t glyph){buffer->info[i].codepoint = glyph;+ if (glyph == DELETED_GLYPH)+ {+ buffer->scratch_flags |= HB_BUFFER_SCRATCH_FLAG_AAT_HAS_DELETED;+ _hb_glyph_info_set_aat_deleted (&buffer->info[i]);+ }if (likely (using_buffer_glyph_set))buffer_glyph_set->add (glyph);#ifndef HB_NO_OT_LAYOUT@@ -792,7 +814,7 @@ struct Lookuppublic:DEFINE_SIZE_UNION (2, format.v);};-DECLARE_NULL_NAMESPACE_BYTES_TEMPLATE1 (AAT, Lookup, 2);+DECLARE_NULL_NAMESPACE_BYTES_TEMPLATE1 (AAT, Lookup, 13);/** (Extended) State Table@@ -1134,31 +1156,37 @@ struct ObsoleteTypestypedef ClassTable<HBUINT16> ClassTypeWide;template <typename T>- static unsigned int offsetToIndex (unsigned int offset,- const void *base,- const T *array)+ static int offsetToIndex (int64_t offset,+ const void *base,+ const T *array){+ int64_t array_offset = (const char *) array - (const char *) base;+ int bad_index = INT_MAX / T::static_size;+/* https://github.com/harfbuzz/harfbuzz/issues/3483 *//* If offset is less than base, return an offset that would* result in an address half a 32bit address-space away,* to make sure sanitize fails even on 32bit builds. */- if (unlikely (offset < unsigned ((const char *) array - (const char *) base)))- return INT_MAX / T::static_size;+ if (unlikely (offset < array_offset))+ return bad_index;/* https://github.com/harfbuzz/harfbuzz/issues/2816 */- return (offset - unsigned ((const char *) array - (const char *) base)) / T::static_size;+ int64_t index = (offset - array_offset) / T::static_size;+ if (unlikely (index > bad_index))+ return bad_index;+ return index;}template <typename T>- static unsigned int byteOffsetToIndex (unsigned int offset,- const void *base,- const T *array)+ static int byteOffsetToIndex (int64_t offset,+ const void *base,+ const T *array){return offsetToIndex (offset, base, array);}template <typename T>- static unsigned int wordOffsetToIndex (unsigned int offset,- const void *base,- const T *array)+ static int wordOffsetToIndex (int64_t offset,+ const void *base,+ const T *array){return offsetToIndex (2 * offset, base, array);}diff --git a/thirdparty/harfbuzz/src/hb-aat-layout-feat-table.hh b/thirdparty/harfbuzz/src/hb-aat-layout-feat-table.hhindex 4fbec332eb7..2f02de338d4 100644--- a/thirdparty/harfbuzz/src/hb-aat-layout-feat-table.hh+++ b/thirdparty/harfbuzz/src/hb-aat-layout-feat-table.hh@@ -114,7 +114,7 @@ struct FeatureNameif (pdefault_index)*pdefault_index = default_index;- if (selectors_count)+ if (selectors_count && selectors){+ settings_table.sub_array (start_offset, selectors_count)| hb_map ([=] (const SettingName& setting) { return setting.get_info (default_selector); })@@ -168,7 +168,7 @@ struct featunsigned int *count,hb_aat_layout_feature_type_t *features) const{- if (count)+ if (count && features){+ namesZ.as_array (featureNameCount).sub_array (start_offset, count)| hb_map (&FeatureName::get_feature_type)diff --git a/thirdparty/harfbuzz/src/hb-aat-layout-kerx-table.hh b/thirdparty/harfbuzz/src/hb-aat-layout-kerx-table.hhindex 7ff003f7158..5d5b2e17344 100644--- a/thirdparty/harfbuzz/src/hb-aat-layout-kerx-table.hh+++ b/thirdparty/harfbuzz/src/hb-aat-layout-kerx-table.hh@@ -258,6 +258,7 @@ struct KerxSubTableFormat1depth (0),crossStream (table->header.coverage & table->header.CrossStream) {}+ HB_AAT_TRANSITION_INLINEvoid transition (hb_buffer_t *buffer,StateTableDriver<Types, EntryData, Flags> *driver,const Entry<EntryData> &entry)@@ -322,15 +323,15 @@ struct KerxSubTableFormat1}else if (o.attach_type()){- o.y_offset += c->font->em_scale_y (v);+ o.y_offset = hb_saturate_add (o.y_offset, c->font->em_scale_y (v));buffer->scratch_flags |= HB_BUFFER_SCRATCH_FLAG_HAS_GPOS_ATTACHMENT;}}else if (buffer->info[idx].mask & kern_mask){auto scaled = c->font->em_scale_x (v);- o.x_advance += scaled;- o.x_offset += scaled;+ o.x_advance = hb_saturate_add (o.x_advance, scaled);+ o.x_offset = hb_saturate_add (o.x_offset, scaled);}}else@@ -346,14 +347,15 @@ struct KerxSubTableFormat1}else if (o.attach_type()){- o.x_offset += c->font->em_scale_x (v);+ o.x_offset = hb_saturate_add (o.x_offset, c->font->em_scale_x (v));buffer->scratch_flags |= HB_BUFFER_SCRATCH_FLAG_HAS_GPOS_ATTACHMENT;}}else if (buffer->info[idx].mask & kern_mask){- o.y_advance += c->font->em_scale_y (v);- o.y_offset += c->font->em_scale_y (v);+ auto scaled = c->font->em_scale_y (v);+ o.y_advance = hb_saturate_add (o.y_advance, scaled);+ o.y_offset = hb_saturate_add (o.y_offset, scaled);}}}@@ -550,6 +552,7 @@ struct KerxSubTableFormat4mark_set (false),mark (0) {}+ HB_AAT_TRANSITION_INLINEvoid transition (hb_buffer_t *buffer,StateTableDriver<Types, EntryData, Flags> *driver,const Entry<EntryData> &entry)@@ -583,8 +586,8 @@ struct KerxSubTableFormat4&currX, &currY))return;- o.x_offset = markX - currX;- o.y_offset = markY - currY;+ o.x_offset = hb_saturate_sub (markX, currX);+ o.y_offset = hb_saturate_sub (markY, currY);}break;@@ -605,8 +608,10 @@ struct KerxSubTableFormat4currAnchorPoint,c->sanitizer.get_num_glyphs ());- o.x_offset = c->font->em_scale_x (markAnchor.xCoordinate) - c->font->em_scale_x (currAnchor.xCoordinate);- o.y_offset = c->font->em_scale_y (markAnchor.yCoordinate) - c->font->em_scale_y (currAnchor.yCoordinate);+ o.x_offset = hb_saturate_sub (c->font->em_scale_x (markAnchor.xCoordinate),+ c->font->em_scale_x (currAnchor.xCoordinate));+ o.y_offset = hb_saturate_sub (c->font->em_scale_y (markAnchor.yCoordinate),+ c->font->em_scale_y (currAnchor.yCoordinate));}break;@@ -622,8 +627,8 @@ struct KerxSubTableFormat4int currX = *data++;int currY = *data++;- o.x_offset = c->font->em_scale_x (markX) - c->font->em_scale_x (currX);- o.y_offset = c->font->em_scale_y (markY) - c->font->em_scale_y (currY);+ o.x_offset = hb_saturate_sub (c->font->em_scale_x (markX), c->font->em_scale_x (currX));+ o.y_offset = hb_saturate_sub (c->font->em_scale_y (markY), c->font->em_scale_y (currY));}break;}@@ -870,11 +875,11 @@ struct KerxSubTableunsigned int subtable_type = get_type ();TRACE_DISPATCH (this, subtable_type);switch (subtable_type) {- case 0: return_trace (c->dispatch (u.format0, std::forward<Ts> (ds)...));- case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));- case 2: return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));- case 4: return_trace (c->dispatch (u.format4, std::forward<Ts> (ds)...));- case 6: return_trace (c->dispatch (u.format6, std::forward<Ts> (ds)...));+ case 0: hb_barrier (); return_trace (c->dispatch (u.format0, std::forward<Ts> (ds)...));+ case 1: hb_barrier (); return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));+ case 2: hb_barrier (); return_trace (c->dispatch (u.format2, std::forward<Ts> (ds)...));+ case 4: hb_barrier (); return_trace (c->dispatch (u.format4, std::forward<Ts> (ds)...));+ case 6: hb_barrier (); return_trace (c->dispatch (u.format6, std::forward<Ts> (ds)...));default: return_trace (c->default_return_value ());}}@@ -884,11 +889,11 @@ struct KerxSubTable{unsigned int subtable_type = get_type ();switch (subtable_type) {- case 0: u.format0.collect_glyphs (first_set, second_set, num_glyphs); return;- case 1: u.format1.collect_glyphs (first_set, second_set, num_glyphs); return;- case 2: u.format2.collect_glyphs (first_set, second_set, num_glyphs); return;- case 4: u.format4.collect_glyphs (first_set, second_set, num_glyphs); return;- case 6: u.format6.collect_glyphs (first_set, second_set, num_glyphs); return;+ case 0: hb_barrier (); u.format0.collect_glyphs (first_set, second_set, num_glyphs); return;+ case 1: hb_barrier (); u.format1.collect_glyphs (first_set, second_set, num_glyphs); return;+ case 2: hb_barrier (); u.format2.collect_glyphs (first_set, second_set, num_glyphs); return;+ case 4: hb_barrier (); u.format4.collect_glyphs (first_set, second_set, num_glyphs); return;+ case 6: hb_barrier (); u.format6.collect_glyphs (first_set, second_set, num_glyphs); return;default: return;}}diff --git a/thirdparty/harfbuzz/src/hb-aat-layout-morx-table.hh b/thirdparty/harfbuzz/src/hb-aat-layout-morx-table.hhindex c56bdb7c7a8..aa608113173 100644--- a/thirdparty/harfbuzz/src/hb-aat-layout-morx-table.hh+++ b/thirdparty/harfbuzz/src/hb-aat-layout-morx-table.hh@@ -84,6 +84,7 @@ struct RearrangementSubtabletable (table_),start (0), end (0) {}+ HB_AAT_TRANSITION_INLINEvoid transition (hb_buffer_t *buffer,StateTableDriver<Types, EntryData, Flags> *driver,const Entry<EntryData> &entry)@@ -200,10 +201,12 @@ struct ContextualSubtablestruct EntryData{- HBUINT16 markIndex; /* Index of the substitution table for the- * marked glyph (use 0xFFFF for none). */- HBUINT16 currentIndex; /* Index of the substitution table for the- * current glyph (use 0xFFFF for none). */+ typedef typename std::conditional<Types::extended, HBUINT16, HBINT16>::type OffsetType;++ OffsetType markIndex; /* Index/offset of the substitution table for the+ * marked glyph. */+ OffsetType currentIndex; /* Index/offset of the substitution table for the+ * current glyph. */public:DEFINE_SIZE_STATIC (4);};@@ -222,7 +225,10 @@ struct ContextualSubtable}bool is_actionable (const Entry<EntryData> &entry) const{- return entry.data.markIndex != 0xFFFF || entry.data.currentIndex != 0xFFFF;+ if (Types::extended)+ return entry.data.markIndex != 0xFFFF || entry.data.currentIndex != 0xFFFF;+ else+ return entry.data.markIndex || entry.data.currentIndex;}struct driver_context_t@@ -238,6 +244,7 @@ struct ContextualSubtablemark (0),subs (table+table->substitutionTables) {}+ HB_AAT_TRANSITION_INLINEvoid transition (hb_buffer_t *buffer,StateTableDriver<Types, EntryData, Flags> *driver,const Entry<EntryData> &entry)@@ -260,13 +267,16 @@ struct ContextualSubtable}else{- unsigned int offset = entry.data.markIndex + buffer->info[mark].codepoint;- const UnsizedArrayOf<HBGlyphID16> &subs_old = (const UnsizedArrayOf<HBGlyphID16> &) subs;- replacement = &subs_old[Types::wordOffsetToIndex (offset, table, subs_old.arrayZ)];- if (!(replacement->sanitize (&c->sanitizer) &&- hb_barrier () &&- *replacement))- replacement = nullptr;+ if (entry.data.markIndex)+ {+ int offset = (int) entry.data.markIndex + buffer->info[mark].codepoint;+ const UnsizedArrayOf<HBGlyphID16> &subs_old = (const UnsizedArrayOf<HBGlyphID16> &) subs;+ replacement = &subs_old[Types::wordOffsetToIndex (offset, table, subs_old.arrayZ)];+ if (!(replacement->sanitize (&c->sanitizer) &&+ hb_barrier () &&+ *replacement))+ replacement = nullptr;+ }}if (replacement){@@ -287,13 +297,16 @@ struct ContextualSubtable}else{- unsigned int offset = entry.data.currentIndex + buffer->info[idx].codepoint;- const UnsizedArrayOf<HBGlyphID16> &subs_old = (const UnsizedArrayOf<HBGlyphID16> &) subs;- replacement = &subs_old[Types::wordOffsetToIndex (offset, table, subs_old.arrayZ)];- if (!(replacement->sanitize (&c->sanitizer) &&- hb_barrier () &&- *replacement))- replacement = nullptr;+ if (entry.data.currentIndex)+ {+ int offset = (int) entry.data.currentIndex + buffer->info[idx].codepoint;+ const UnsizedArrayOf<HBGlyphID16> &subs_old = (const UnsizedArrayOf<HBGlyphID16> &) subs;+ replacement = &subs_old[Types::wordOffsetToIndex (offset, table, subs_old.arrayZ)];+ if (!(replacement->sanitize (&c->sanitizer) &&+ hb_barrier () &&+ *replacement))+ replacement = nullptr;+ }}if (replacement){@@ -479,6 +492,7 @@ struct LigatureSubtableligature (table+table->ligature),match_length (0) {}+ HB_AAT_TRANSITION_INLINEvoid transition (hb_buffer_t *buffer,StateTableDriver<Types, EntryData, Flags> *driver,const Entry<EntryData> &entry)@@ -776,6 +790,7 @@ struct InsertionSubtablemark (0),insertionAction (table+table->insertionAction) {}+ HB_AAT_TRANSITION_INLINEvoid transition (hb_buffer_t *buffer,StateTableDriver<Types, EntryData, Flags> *driver,const Entry<EntryData> &entry)@@ -1067,11 +1082,11 @@ struct ChainSubtableunsigned int subtable_type = get_type ();TRACE_DISPATCH (this, subtable_type);switch (subtable_type) {- case Rearrangement: return_trace (c->dispatch (u.rearrangement, std::forward<Ts> (ds)...));- case Contextual: return_trace (c->dispatch (u.contextual, std::forward<Ts> (ds)...));- case Ligature: return_trace (c->dispatch (u.ligature, std::forward<Ts> (ds)...));- case Noncontextual: return_trace (c->dispatch (u.noncontextual, std::forward<Ts> (ds)...));- case Insertion: return_trace (c->dispatch (u.insertion, std::forward<Ts> (ds)...));+ case Rearrangement: hb_barrier (); return_trace (c->dispatch (u.rearrangement, std::forward<Ts> (ds)...));+ case Contextual: hb_barrier (); return_trace (c->dispatch (u.contextual, std::forward<Ts> (ds)...));+ case Ligature: hb_barrier (); return_trace (c->dispatch (u.ligature, std::forward<Ts> (ds)...));+ case Noncontextual: hb_barrier (); return_trace (c->dispatch (u.noncontextual, std::forward<Ts> (ds)...));+ case Insertion: hb_barrier (); return_trace (c->dispatch (u.insertion, std::forward<Ts> (ds)...));default: return_trace (c->default_return_value ());}}diff --git a/thirdparty/harfbuzz/src/hb-aat-layout-trak-table.hh b/thirdparty/harfbuzz/src/hb-aat-layout-trak-table.hhindex 14a7d579447..104a346d460 100644--- a/thirdparty/harfbuzz/src/hb-aat-layout-trak-table.hh+++ b/thirdparty/harfbuzz/src/hb-aat-layout-trak-table.hh@@ -230,13 +230,13 @@ struct trak{hb_position_t advance_to_add = get_h_tracking (c->font, track);foreach_grapheme (buffer, start, end)- buffer->pos[start].x_advance += advance_to_add;+ buffer->pos[start].x_advance = hb_saturate_add (buffer->pos[start].x_advance, advance_to_add);}else{hb_position_t advance_to_add = get_v_tracking (c->font, track);foreach_grapheme (buffer, start, end)- buffer->pos[start].y_advance += advance_to_add;+ buffer->pos[start].y_advance = hb_saturate_add (buffer->pos[start].y_advance, advance_to_add);}return_trace (true);diff --git a/thirdparty/harfbuzz/src/hb-aat-layout.cc b/thirdparty/harfbuzz/src/hb-aat-layout.ccindex a48c4e0bcfe..d6e75861215 100644--- a/thirdparty/harfbuzz/src/hb-aat-layout.cc+++ b/thirdparty/harfbuzz/src/hb-aat-layout.cc@@ -411,7 +411,7 @@ hb_aat_layout_track (const hb_ot_shape_plan_t *plan,* @start_offset: offset of the first feature type to retrieve* @feature_count: (inout) (optional): Input = the maximum number of feature types to return;* Output = the actual number of feature types returned (may be zero)- * @features: (out caller-allocates) (array length=feature_count): Array of feature types found+ * @features: (out caller-allocates) (array length=feature_count) (nullable): Array of feature types found** Fetches a list of the AAT feature types included in the specified face.*diff --git a/thirdparty/harfbuzz/src/hb-algs.hh b/thirdparty/harfbuzz/src/hb-algs.hhindex d35a723f727..31361d8b344 100644--- a/thirdparty/harfbuzz/src/hb-algs.hh+++ b/thirdparty/harfbuzz/src/hb-algs.hh@@ -39,6 +39,19 @@#include <functional>#include <new>+static HB_ALWAYS_INLINE void *+hb_malloc2 (size_t nmemb, size_t size)+{+ if (size && nmemb > SIZE_MAX / size) return nullptr;+ return hb_malloc (nmemb * size);+}+static HB_ALWAYS_INLINE void *+hb_realloc2 (void *ptr, size_t nmemb, size_t size)+{+ if (size && nmemb > SIZE_MAX / size) return nullptr;+ return hb_realloc (ptr, nmemb * size);+}+/** Flags*/@@ -877,6 +890,94 @@ struct}HB_FUNCOBJ (hb_clamp);+/* Signed saturating arithmetic. */+template <typename T>+static HB_ALWAYS_INLINE T+hb_saturate_add (T a, T b)+{+ static_assert (std::is_integral<T>::value && std::is_signed<T>::value, "");++#if hb_has_builtin(__builtin_add_overflow)+ T result;+ if (likely (!__builtin_add_overflow (a, b, &result)))+ return result;+#else+ if (b > 0)+ {+ if (likely (a <= hb_int_max (T) - b))+ return a + b;+ }+ else if (likely (a >= hb_int_min (T) - b))+ return a + b;+#endif++ return a < 0 ? hb_int_min (T) : hb_int_max (T);+}++template <typename T>+static HB_ALWAYS_INLINE T+hb_saturate_sub (T a, T b)+{+ static_assert (std::is_integral<T>::value && std::is_signed<T>::value, "");++#if hb_has_builtin(__builtin_sub_overflow)+ T result;+ if (likely (!__builtin_sub_overflow (a, b, &result)))+ return result;+#else+ if (b > 0)+ {+ if (likely (a >= hb_int_min (T) + b))+ return a - b;+ }+ else if (likely (a <= hb_int_max (T) + b))+ return a - b;+#endif++ return b < 0 ? hb_int_max (T) : hb_int_min (T);+}++template <typename T>+static HB_ALWAYS_INLINE T+hb_saturate_neg (T a)+{+ static_assert (std::is_integral<T>::value && std::is_signed<T>::value, "");++ return hb_saturate_sub ((T) 0, a);+}++/* Convert a floating-point value to integer type T, saturating to T's+ * range instead of relying on the undefined behavior of an out-of-range+ * float-to-int conversion. NaN saturates to the minimum of T. */+template <typename T>+static HB_ALWAYS_INLINE T+hb_clamp_to (double v)+{+ return (T) hb_clamp (v,+ (double) hb_int_min (T),+ (double) hb_int_max (T));+}++template <typename T>+static HB_ALWAYS_INLINE T+hb_clamp_to (float v)+{+ /* Widen explicitly: float cannot represent all integer bounds exactly,+ * so the clamp itself is done in double. */+ return hb_clamp_to<T> ((double) v);+}++template <typename T>+static HB_ALWAYS_INLINE T+hb_clamp_to (int64_t v)+{+ static_assert (std::is_integral<T>::value && std::is_signed<T>::value, "");++ return (T) hb_clamp (v,+ (int64_t) hb_int_min (T),+ (int64_t) hb_int_max (T));+}+/** Bithacks.*/@@ -1215,6 +1316,62 @@ hb_unsigned_add_overflows (unsigned int a, unsigned int b, unsigned *result = nureturn b > (unsigned int) -1 - a;}+/* Saturating arithmetic on size_t. On platforms where size_t is wider than+ * unsigned int (i.e. 64-bit), the inputs to get_size()-style computations+ * (counts and static_sizes which are at most 32-bit) cannot overflow size_t,+ * so these reduce to plain arithmetic. On 32-bit platforms (size_t is+ * unsigned int), they saturate to SIZE_MAX so sanitize/serialize callers+ * naturally reject the resulting size as out-of-range. */++static inline size_t+hb_unsigned_mul_saturate (size_t a, size_t b)+{+ if (sizeof (size_t) > sizeof (unsigned int))+ return a * b;+#if hb_has_builtin(__builtin_mul_overflow)+ size_t result;+ if (__builtin_mul_overflow (a, b, &result))+ return (size_t) -1;+ return result;+#else+ if (b > 0 && a > ((size_t) -1) / b) return (size_t) -1;+ return a * b;+#endif+}++static inline size_t+hb_unsigned_add_saturate (size_t a, size_t b)+{+ if (sizeof (size_t) > sizeof (unsigned int))+ return a + b;+#if hb_has_builtin(__builtin_add_overflow)+ size_t result;+ if (__builtin_add_overflow (a, b, &result))+ return (size_t) -1;+ return result;+#else+ if (b > ((size_t) -1) - a) return (size_t) -1;+ return a + b;+#endif+}++/* Variadic forms: fold left across all arguments. */+template <typename ...Ts>+static inline size_t+hb_unsigned_mul_saturate (size_t a, size_t b, size_t c, Ts... rest)+{ return hb_unsigned_mul_saturate (hb_unsigned_mul_saturate (a, b), c, rest...); }++template <typename ...Ts>+static inline size_t+hb_unsigned_add_saturate (size_t a, size_t b, size_t c, Ts... rest)+{ return hb_unsigned_add_saturate (hb_unsigned_add_saturate (a, b), c, rest...); }++/* Saturating mul-add: a * b + c. Covers the dominant get_size() pattern+ * `count * static_size + min_size`. */+static inline size_t+hb_unsigned_mul_add_saturate (size_t a, size_t b, size_t c)+{ return hb_unsigned_add_saturate (hb_unsigned_mul_saturate (a, b), c); }+/** Sort and search.@@ -1305,143 +1462,87 @@ hb_bsearch (const K& key, V* base,}-/* From https://github.com/noporpoise/sort_r- Feb 5, 2019 (c8c65c1e)- Modified to support optional argument using templates */--/* Isaac Turner 29 April 2014 Public Domain */--/*-hb_qsort function to be exported.-Parameters:- base is the array to be sorted- nel is the number of elements in the array- width is the size in bytes of each element of the array- compar is the comparison function- arg (optional) is a pointer to be passed to the comparison function--void hb_qsort(void *base, size_t nel, size_t width,- int (*compar)(const void *_a, const void *_b, [void *_arg]),- [void *arg]);-*/--#define SORT_R_SWAP(a,b,tmp) ((void) ((tmp) = (a)), (void) ((a) = (b)), (b) = (tmp))--/* swap a and b */-/* a and b must not be equal! */-static inline void sort_r_swap(char *__restrict a, char *__restrict b,- size_t w)-{- char tmp, *end = a+w;- for(; a < end; a++, b++) { SORT_R_SWAP(*a, *b, tmp); }-}--/* swap a, b iff a>b */-/* a and b must not be equal! */-/* __restrict is same as restrict but better support on old machines */-template <typename Compar>-static inline int sort_r_cmpswap(char *__restrict a,- char *__restrict b, size_t w,- Compar compar)-{- if(compar(a, b) > 0) {- sort_r_swap(a, b, w);- return 1;- }- return 0;-}--/*-Swap consecutive blocks of bytes of size na and nb starting at memory addr ptr,-with the smallest swap so that the blocks are in the opposite order. Blocks may-be internally re-ordered e.g.- 12345ab -> ab34512- 123abc -> abc123- 12abcde -> deabc12-*/-static inline void sort_r_swap_blocks(char *ptr, size_t na, size_t nb)-{- if(na > 0 && nb > 0) {- if(na > nb) { sort_r_swap(ptr, ptr+na, nb); }- else { sort_r_swap(ptr, ptr+nb, na); }- }-}--/* Implement recursive quicksort ourselves */-/* Note: quicksort is not stable, equivalent values may be swapped */-template <typename Compar>-static inline void sort_r_simple(void *base, size_t nel, size_t w,- Compar compar)+/* Quicksort partitioning loop: median-of-three pivot, two-way+ * Hoare partition, tail-call elimination on the larger side.+ * Stops partitioning when subranges shrink below the threshold;+ * a single insertion-sort pass over the whole array (run by the+ * caller) finishes the job. Same structure libstdc++ uses for+ * std::sort.+ *+ * Not stable; equivalent values may be swapped. */+/* Quicksort partitioning loop: median-of-three pivot, two-way+ * Hoare partition, tail-call elimination on the larger side.+ * Stops partitioning when subranges shrink below the threshold;+ * a single insertion-sort pass over the whole array (run by+ * hb_qsort_inline below) finishes the job. Same shape libstdc+++ * uses for std::sort.+ *+ * Not stable; equivalent values may be swapped. */+template <typename T, typename Compar>+static inline void+hb_qsort_loop (T *base, size_t nel, Compar compar){- char *b = (char *)base, *end = b + nel*w;-- if(nel < 10) {- /* Insertion sort for arbitrarily small inputs */- char *pi, *pj;- for(pi = b+w; pi < end; pi += w) {- for(pj = pi; pj > b && sort_r_cmpswap(pj-w,pj,w,compar); pj -= w) {}- }- }- else+ while (nel > 24){- /* nel > 9; Quicksort */-- int cmp;- char *pl, *ple, *pr, *pre, *pivot;- char *last = b+w*(nel-1), *tmp;+ T *last = base + nel - 1;+ T *mid = base + nel / 2;- char *l[3];- l[0] = b + w;- l[1] = b+w*(nel/2);- l[2] = last - w;-- if(compar(l[0],l[1]) > 0) { SORT_R_SWAP(l[0], l[1], tmp); }- if(compar(l[1],l[2]) > 0) {- SORT_R_SWAP(l[1], l[2], tmp);- if(compar(l[0],l[1]) > 0) { SORT_R_SWAP(l[0], l[1], tmp); }+ /* Median-of-three pivot, parked at last-1. */+ if (compar (*base, *mid) > 0) hb_swap (*base, *mid);+ if (compar (*mid, *last) > 0)+ {+ hb_swap (*mid, *last);+ if (compar (*base, *mid) > 0) hb_swap (*base, *mid);}-- if(l[1] != last) { sort_r_swap(l[1], last, w); }-- pivot = last;- ple = pl = b;- pre = pr = last;-- while(pl < pr) {- for(; pl < pr; pl += w) {- cmp = compar(pl, pivot);- if(cmp > 0) { break; }- else if(cmp == 0) {- if(ple < pl) { sort_r_swap(ple, pl, w); }- ple += w;- }- }- if(pl >= pr) { break; }- for(; pl < pr; ) {- pr -= w;- cmp = compar(pr, pivot);- if(cmp == 0) {- pre -= w;- if(pr < pre) { sort_r_swap(pr, pre, w); }- }- else if(cmp < 0) {- if(pl < pr) { sort_r_swap(pl, pr, w); }- pl += w;- break;- }- }+ hb_swap (*mid, *(last - 1));+ T &pivot = *(last - 1);++ /* Two-way Hoare partition. Inner loops are unguarded:+ * median-of-three left *base <= pivot and *last >= pivot,+ * which act as sentinels. */+ T *i = base, *j = last - 1;+ while (true)+ {+ while (compar (*++i, pivot) < 0) {}+ while (compar (*--j, pivot) > 0) {}+ if (i >= j) break;+ hb_swap (*i, *j);}+ hb_swap (*i, *(last - 1));- pl = pr;-- sort_r_swap_blocks(b, ple-b, pl-ple);- sort_r_swap_blocks(pr, pre-pr, end-pre);-- sort_r_simple(b, (pl-ple)/w, w, compar);- sort_r_simple(end-(pre-pr), (pre-pr)/w, w, compar);+ /* Recurse on smaller side, loop on larger — bounds stack+ * depth at O(log n). */+ size_t left = (size_t) (i - base);+ size_t right = nel - left - 1;+ if (left < right)+ {+ hb_qsort_loop (base, left, compar);+ base = i + 1;+ nel = right;+ }+ else+ {+ hb_qsort_loop (i + 1, right, compar);+ nel = left;+ }}}+template <typename T, typename Compar>+static inline void+hb_qsort_inline (T *base, size_t nel, Compar compar)+{+ hb_qsort_loop (base, nel, compar);++ /* Single final insertion sort over the whole array. After+ * the partitioning loop, every element is within the threshold+ * of its sorted position, so this pass is O(n * threshold). */+ T *end = base + nel;+ for (T *pi = base + 1; pi < end; pi++)+ for (T *pj = pi; pj > base && compar (pj[-1], pj[0]) > 0; pj--)+ hb_swap (pj[-1], pj[0]);+}+static inline voidhb_qsort (void *base, size_t nel, size_t width,int (*compar)(const void *_a, const void *_b))diff --git a/thirdparty/harfbuzz/src/hb-array.hh b/thirdparty/harfbuzz/src/hb-array.hhindex 2799d84910b..685e866637f 100644--- a/thirdparty/harfbuzz/src/hb-array.hh+++ b/thirdparty/harfbuzz/src/hb-array.hh@@ -32,8 +32,6 @@#include "hb-iter.hh"#include "hb-null.hh"-#include <algorithm>-template <typename Type>struct hb_sorted_array_t;@@ -227,22 +225,14 @@ struct hb_array_t : hb_iter_with_fallback_t<hb_array_t<Type>, Type&>hb_qsort (arrayZ, length, this->get_item_size (), cmp);return hb_sorted_array_t<Type> (*this);}- /* std::sort wants a strict-weak `a < b` boolean, but our other- * qsort overload (and most existing call sites) follow the C- * qsort convention of returning negative / zero / positive ints.- * Adapt to either via overload resolution: bool passes through;- * any other arithmetic return type is treated as the int signed- * comparator. */- template <typename T> static bool _qsort_lt (T v) { return v < 0; }- static bool _qsort_lt (bool v) { return v; }+ /* Comparator follows the C qsort convention: returns+ * negative / zero / positive int. */template <typename Compar>hb_sorted_array_t<Type> qsort (Compar compar){if (likely (length))- std::sort (arrayZ, arrayZ + length,- [&] (const Type &a, const Type &b)- { return _qsort_lt (compar (a, b)); });+ hb_qsort_inline (arrayZ, length, compar);return hb_sorted_array_t<Type> (*this);}@@ -251,7 +241,7 @@ struct hb_array_t : hb_iter_with_fallback_t<hb_array_t<Type>, Type&>hb_enable_if (std::is_move_assignable<T>::value)>hb_sorted_array_t<Type> _qsort (hb_priority<1>){- return qsort ([] (const Type &a, const Type &b) { return Type::cmp (&a, &b) < 0; });+ return qsort ([] (const Type &a, const Type &b) { return Type::cmp (&a, &b); });}hb_sorted_array_t<Type> _qsort (hb_priority<0>){diff --git a/thirdparty/harfbuzz/src/hb-bit-page.hh b/thirdparty/harfbuzz/src/hb-bit-page.hhindex 16d5886a2cd..8a4ad58cf71 100644--- a/thirdparty/harfbuzz/src/hb-bit-page.hh+++ b/thirdparty/harfbuzz/src/hb-bit-page.hh@@ -135,7 +135,9 @@ struct hb_bit_page_t}void add (hb_codepoint_t g) { elt (g) |= mask (g); dirty (); }+ void add_bits (hb_codepoint_t g, uint64_t bits) { elt (g) |= bits; dirty (); }void del (hb_codepoint_t g) { elt (g) &= ~mask (g); dirty (); }+ void del_bits (hb_codepoint_t g, uint64_t bits) { elt (g) &= ~bits; dirty (); }void set (hb_codepoint_t g, bool value) { if (value) add (g); else del (g); }bool get (hb_codepoint_t g) const { return elt (g) & mask (g); }bool may_have (hb_codepoint_t g) const { return get (g); }@@ -150,7 +152,7 @@ struct hb_bit_page_telt_t *lb = &elt (b);if (la == lb)*la |= (mask (b) << 1) - mask(a);- else+ else if (likely (la < lb)){*la |= ~(mask (a) - 1llu);la++;@@ -159,6 +161,8 @@ struct hb_bit_page_t*lb |= ((mask (b) << 1) - 1llu);}+ else+ return;dirty ();}void del_range (hb_codepoint_t a, hb_codepoint_t b)@@ -167,7 +171,7 @@ struct hb_bit_page_telt_t *lb = &elt (b);if (la == lb)*la &= ~((mask (b) << 1llu) - mask(a));- else+ else if (likely (la < lb)){*la &= mask (a) - 1;la++;@@ -176,6 +180,8 @@ struct hb_bit_page_t*lb &= ~((mask (b) << 1) - 1llu);}+ else+ return;dirty ();}void set_range (hb_codepoint_t a, hb_codepoint_t b, bool v)diff --git a/thirdparty/harfbuzz/src/hb-bit-set-invertible.hh b/thirdparty/harfbuzz/src/hb-bit-set-invertible.hhindex 48b2e218423..089c73c2c39 100644--- a/thirdparty/harfbuzz/src/hb-bit-set-invertible.hh+++ b/thirdparty/harfbuzz/src/hb-bit-set-invertible.hh@@ -101,9 +101,20 @@ struct hb_bit_set_invertible_t}unsigned int get_population () const{ return inverted ? INVALID - s.get_population () : s.get_population (); }+ bool get_singleton (hb_codepoint_t *codepoint) const+ {+ if (likely (!inverted))+ return s.get_singleton (codepoint);+ if (s.get_population () != INVALID - 1)+ return false;+ *codepoint = get_min ();+ return *codepoint != INVALID;+ }void add (hb_codepoint_t g) { unlikely (inverted) ? s.del (g) : s.add (g); }+ void add_bits (hb_codepoint_t g, uint64_t bits)+ { unlikely (inverted) ? s.del_bits (g, bits) : s.add_bits (g, bits); }bool add_range (hb_codepoint_t a, hb_codepoint_t b){ return unlikely (inverted) ? ((void) s.del_range (a, b), true) : s.add_range (a, b); }@@ -143,6 +154,24 @@ struct hb_bit_set_invertible_tbool may_intersect (const hb_bit_set_invertible_t &other) const{ return inverted || other.inverted || s.intersects (other.s); }+ bool intersects (const hb_bit_set_invertible_t &other) const+ {+ if (likely (!inverted))+ return unlikely (other.inverted) ? !s.is_subset (other.s)+ : s.intersects (other.s);+ if (likely (!other.inverted))+ return !other.s.is_subset (s);++ unsigned population = s.get_population ();+ unsigned other_population = other.s.get_population ();+ if ((uint64_t) population + other_population < INVALID)+ return true;++ return population >= other_population+ ? !hb_all (iter (), other.s)+ : !hb_all (other.iter (), s);+ }+bool intersects (hb_codepoint_t first, hb_codepoint_t last) const{hb_codepoint_t c = first - 1;@@ -187,8 +216,10 @@ struct hb_bit_set_invertible_tprotected:template <typename Op>- void process (const Op& op, const hb_bit_set_invertible_t &other)- { s.process (op, other.s); }+ void process (const Op& op,+ const hb_bit_set_invertible_t &other,+ hb_vector_t<unsigned> *workspace = nullptr)+ { s.process (op, other.s, workspace); }public:void union_ (const hb_bit_set_invertible_t &other){@@ -209,21 +240,22 @@ struct hb_bit_set_invertible_tif (likely (s.successful))inverted = inverted || other.inverted;}- void intersect (const hb_bit_set_invertible_t &other)+ void intersect (const hb_bit_set_invertible_t &other,+ hb_vector_t<unsigned> *workspace = nullptr){if (likely (inverted == other.inverted)){if (unlikely (inverted))- process (hb_bitwise_or, other);+ process (hb_bitwise_or, other, workspace);else- process (hb_bitwise_and, other); /* Main branch. */+ process (hb_bitwise_and, other, workspace); /* Main branch. */}else{if (unlikely (inverted))- process (hb_bitwise_lt, other);+ process (hb_bitwise_lt, other, workspace);else- process (hb_bitwise_gt, other);+ process (hb_bitwise_gt, other, workspace);}if (likely (s.successful))inverted = inverted && other.inverted;@@ -280,6 +312,47 @@ struct hb_bit_set_invertible_t*codepoint = v + 1;return *codepoint != INVALID;}+ bool next_bits (hb_codepoint_t *codepoint, uint64_t *bits) const+ {+ if (likely (!inverted))+ return s.next_bits (codepoint, bits);++ hb_codepoint_t base;+ if (unlikely (*codepoint == INVALID))+ base = 0;+ else+ {+ base = *codepoint & -hb_bit_page_t::ELT_BITS;+ if (unlikely (base >= INVALID - hb_bit_page_t::ELT_BITS + 1))+ goto done;+ base += hb_bit_page_t::ELT_BITS;+ }++ while (true)+ {+ hb_codepoint_t cursor = base ? base - hb_bit_page_t::ELT_BITS : INVALID;+ uint64_t excluded = 0;+ if (!s.next_bits (&cursor, &excluded) || cursor != base)+ excluded = 0;+ *bits = ~excluded;+ bool last = unlikely (base >= INVALID - hb_bit_page_t::ELT_BITS + 1);+ if (last)+ *bits &= UINT64_MAX >> 1;+ if (*bits)+ {+ *codepoint = base;+ return true;+ }+ if (unlikely (last))+ break;+ base += hb_bit_page_t::ELT_BITS;+ }++ done:+ *codepoint = INVALID;+ *bits = 0;+ return false;+ }bool previous (hb_codepoint_t *codepoint) const{if (likely (!inverted))@@ -352,27 +425,50 @@ struct hb_bit_set_invertible_t/** Iterator implementation.+ * Mutating the set invalidates its iterators.*/struct iter_t : hb_iter_with_fallback_t<iter_t, hb_codepoint_t>{static constexpr bool is_sorted_iterator = true;static constexpr bool has_fast_len = true;iter_t (const hb_bit_set_invertible_t &s_ = Null (hb_bit_set_invertible_t),- bool init = true) : s (&s_), v (INVALID), l(0)+ bool init = true) : s (&s_), v (INVALID), remaining (0),+ have_len (!init), base (INVALID), bits (0){if (init)- {- l = s->get_population () + 1;- __next__ ();- }+ advance ();}typedef hb_codepoint_t __item_t__;hb_codepoint_t __item__ () const { return v; }bool __more__ () const { return v != INVALID; }- void __next__ () { s->next (&v); if (likely (l)) l--; }- void __prev__ () { s->previous (&v); l++; }- unsigned __len__ () const { return l; }+ void __next__ ()+ {+ remaining--;+ advance ();+ }+ void __prev__ ()+ {+ if (s->previous (&v))+ {+ sync ();+ remaining++;+ }+ else+ {+ base = INVALID;+ bits = 0;+ }+ }+ unsigned __len__ () const+ {+ if (unlikely (!have_len))+ {+ remaining += s->get_population ();+ have_len = true;+ }+ return remaining;+ }iter_t end () const { return iter_t (*s, false); }bool operator != (const iter_t& o) const{ return v != o.v; }@@ -380,7 +476,35 @@ struct hb_bit_set_invertible_tprotected:const hb_bit_set_invertible_t *s;hb_codepoint_t v;- unsigned l;+ mutable unsigned remaining;+ mutable bool have_len;+ hb_codepoint_t base;+ uint64_t bits;++ void advance ()+ {+ if (likely (bits))+ {+ v = base + hb_ctz (bits);+ bits &= bits - 1;+ }+ else if (s->next_bits (&base, &bits))+ {+ v = base + hb_ctz (bits);+ bits &= bits - 1;+ }+ else+ v = INVALID;+ }++ void sync ()+ {+ base = v & -hb_bit_page_t::ELT_BITS;+ hb_codepoint_t cursor = base ? base - hb_bit_page_t::ELT_BITS : INVALID;+ s->next_bits (&cursor, &bits);+ unsigned int bit = v & (hb_bit_page_t::ELT_BITS - 1);+ bits = bit == hb_bit_page_t::ELT_BITS - 1 ? 0 : bits >> (bit + 1) << (bit + 1);+ }};iter_t iter () const { return iter_t (*this); }operator iter_t () const { return iter (); }diff --git a/thirdparty/harfbuzz/src/hb-bit-set.hh b/thirdparty/harfbuzz/src/hb-bit-set.hhindex 7525e5a5735..edf8add28cd 100644--- a/thirdparty/harfbuzz/src/hb-bit-set.hh+++ b/thirdparty/harfbuzz/src/hb-bit-set.hh@@ -161,6 +161,14 @@ struct hb_bit_set_tpage_t *page = page_for (g, true); if (unlikely (!page)) return;page->add (g);}+ void add_bits (hb_codepoint_t g, uint64_t bits)+ {+ if (unlikely (!successful) || unlikely (!bits)) return;+ assert (!(g & (page_t::ELT_BITS - 1)));+ dirty ();+ page_t *page = page_for (g, true); if (unlikely (!page)) return;+ page->add_bits (g, bits);+ }bool add_range (hb_codepoint_t a, hb_codepoint_t b){if (unlikely (!successful)) return true; /* https://github.com/harfbuzz/harfbuzz/issues/657 */@@ -291,6 +299,16 @@ struct hb_bit_set_tdirty ();page->del (g);}+ void del_bits (hb_codepoint_t g, uint64_t bits)+ {+ if (unlikely (!successful) || unlikely (!bits)) return;+ assert (!(g & (page_t::ELT_BITS - 1)));+ page_t *page = page_for (g);+ if (!page)+ return;+ dirty ();+ page->del_bits (g, bits);+ }private:void del_pages (int ds, int de)@@ -524,7 +542,8 @@ struct hb_bit_set_tvoid process_ (hb_bit_page_t::vector_t (*op) (const hb_bit_page_t::vector_t &, const hb_bit_page_t::vector_t &),bool passthru_left, bool passthru_right,- const hb_bit_set_t &other)+ const hb_bit_set_t &other,+ hb_vector_t<unsigned> *workspace = nullptr){if (unlikely (!successful)) return;@@ -540,8 +559,18 @@ struct hb_bit_set_t// Pre-allocate the workspace that compact() will need so we can bail on allocation failure// before attempting to rewrite the page map.- hb_vector_t<unsigned> compact_workspace;- if (!passthru_left && unlikely (!allocate_compact_workspace (compact_workspace))) return;+ hb_vector_t<unsigned> local_workspace;+ hb_vector_t<unsigned> &compact_workspace = workspace ? *workspace : local_workspace;+ if (!passthru_left)+ {+ bool allocated = workspace ? compact_workspace.resize (pages.length)+ : allocate_compact_workspace (compact_workspace);+ if (unlikely (!allocated))+ {+ successful = false;+ return;+ }+ }for (; a < na && b < nb; ){@@ -651,13 +680,17 @@ struct hb_bit_set_top_ (const hb_bit_page_t::vector_t &a, const hb_bit_page_t::vector_t &b){ return Op{} (a, b); }template <typename Op>- void process (const Op& op, const hb_bit_set_t &other)+ void process (const Op& op,+ const hb_bit_set_t &other,+ hb_vector_t<unsigned> *workspace = nullptr){- process_ (op_<Op>, op (1, 0), op (0, 1), other);+ process_ (op_<Op>, op (1, 0), op (0, 1), other, workspace);}void union_ (const hb_bit_set_t &other) { process (hb_bitwise_or, other); }- void intersect (const hb_bit_set_t &other) { process (hb_bitwise_and, other); }+ void intersect (const hb_bit_set_t &other,+ hb_vector_t<unsigned> *workspace = nullptr)+ { process (hb_bitwise_and, other, workspace); }void subtract (const hb_bit_set_t &other) { process (hb_bitwise_gt, other); }void symmetric_difference (const hb_bit_set_t &other) { process (hb_bitwise_xor, other); }@@ -708,6 +741,50 @@ struct hb_bit_set_t*codepoint = INVALID;return false;}+ bool next_bits (hb_codepoint_t *codepoint, uint64_t *bits) const+ {+ static_assert (page_t::ELT_BITS == 64, "");++ unsigned int i = 0;+ unsigned int elt = 0;+ if (likely (*codepoint != INVALID))+ {+ hb_codepoint_t base = *codepoint & -page_t::ELT_BITS;+ if (unlikely (base >= INVALID - page_t::ELT_BITS + 1))+ goto done;+ base += page_t::ELT_BITS;++ unsigned int major = get_major (base);+ i = last_page_lookup;+ if (unlikely (i >= page_map.length || page_map.arrayZ[i].major != major))+ {+ page_map.bfind (major, &i, HB_NOT_FOUND_STORE_CLOSEST);+ if (i >= page_map.length)+ goto done;+ }+ if (page_map.arrayZ[i].major == major)+ elt = page_remainder (base) / page_t::ELT_BITS;+ }++ for (; i < page_map.length; i++, elt = 0)+ {+ const page_map_t &map = page_map.arrayZ[i];+ const page_t &page = pages.arrayZ[map.index];+ for (; elt < page_t::len (); elt++)+ if (page.v[elt])+ {+ *codepoint = major_start (map.major) + elt * page_t::ELT_BITS;+ *bits = page.v[elt];+ last_page_lookup = i;+ return true;+ }+ }++ done:+ *codepoint = INVALID;+ *bits = 0;+ return false;+ }bool previous (hb_codepoint_t *codepoint) const{if (unlikely (*codepoint == INVALID)) {@@ -883,6 +960,39 @@ struct hb_bit_set_tpopulation = pop;return pop;}+ bool get_singleton (hb_codepoint_t *codepoint) const+ {+ if (has_population ())+ {+ if (population != 1) return false;+ *codepoint = get_min ();+ return true;+ }++ hb_codepoint_t singleton = INVALID;+ for (const auto &map : page_map)+ {+ const auto &page = pages.arrayZ[map.index];+ for (unsigned i = 0; i < page_t::len (); i++)+ {+ page_t::elt_t bits = page.v[i];+ if (!bits) continue;+ if (singleton != INVALID || (bits & (bits - 1)))+ return false;+ singleton = map.major * page_t::PAGE_BITS ++ i * page_t::ELT_BITS + hb_ctz (bits);+ }+ }++ if (singleton == INVALID)+ {+ population = 0;+ return false;+ }+ population = 1;+ *codepoint = singleton;+ return true;+ }hb_codepoint_t get_min () const{unsigned count = pages.length;diff --git a/thirdparty/harfbuzz/src/hb-blob.cc b/thirdparty/harfbuzz/src/hb-blob.ccindex 3c00808e496..f5d4efd6c84 100644--- a/thirdparty/harfbuzz/src/hb-blob.cc+++ b/thirdparty/harfbuzz/src/hb-blob.cc@@ -662,7 +662,7 @@ _hb_blob_try_mmap (const char *file_name)if (unlikely (!file)) return nullptr;auto file_guard = hb_make_scope_guard ([&]() { hb_free (file); });- unsigned int size = strlen (file_name) + 1;+ size_t size = strlen (file_name) + 1;wchar_t *wchar_file_name = (wchar_t *) hb_malloc (sizeof (wchar_t) * size);if (unlikely (!wchar_file_name)) return nullptr;diff --git a/thirdparty/harfbuzz/src/hb-buffer-serialize.cc b/thirdparty/harfbuzz/src/hb-buffer-serialize.ccindex 923524d708a..108f209c791 100644--- a/thirdparty/harfbuzz/src/hb-buffer-serialize.cc+++ b/thirdparty/harfbuzz/src/hb-buffer-serialize.cc@@ -120,8 +120,8 @@ _hb_buffer_serialize_glyphs_json (hb_buffer_t *buffer,{for (unsigned int i = 0; i < start; i++){- x += pos[i].x_advance;- y += pos[i].y_advance;+ x = hb_saturate_add (x, pos[i].x_advance);+ y = hb_saturate_add (y, pos[i].y_advance);}}@@ -164,8 +164,10 @@ _hb_buffer_serialize_glyphs_json (hb_buffer_t *buffer,if (pos && !(flags & HB_BUFFER_SERIALIZE_FLAG_NO_POSITIONS)){+ hb_position_t dx = hb_saturate_add (x, pos[i].x_offset);+ hb_position_t dy = hb_saturate_add (y, pos[i].y_offset);p += hb_max (0, snprintf (p, ARRAY_LENGTH (b) - (p - b), ",\"dx\":%d,\"dy\":%d",- x+pos[i].x_offset, y+pos[i].y_offset));+ dx, dy));if (!(flags & HB_BUFFER_SERIALIZE_FLAG_NO_ADVANCES))p += hb_max (0, snprintf (p, ARRAY_LENGTH (b) - (p - b), ",\"ax\":%d,\"ay\":%d",pos[i].x_advance, pos[i].y_advance));@@ -206,8 +208,8 @@ _hb_buffer_serialize_glyphs_json (hb_buffer_t *buffer,if (pos && (flags & HB_BUFFER_SERIALIZE_FLAG_NO_ADVANCES)){- x += pos[i].x_advance;- y += pos[i].y_advance;+ x = hb_saturate_add (x, pos[i].x_advance);+ y = hb_saturate_add (y, pos[i].y_advance);}}@@ -289,8 +291,8 @@ _hb_buffer_serialize_glyphs_text (hb_buffer_t *buffer,{for (unsigned int i = 0; i < start; i++){- x += pos[i].x_advance;- y += pos[i].y_advance;+ x = hb_saturate_add (x, pos[i].x_advance);+ y = hb_saturate_add (y, pos[i].y_advance);}}@@ -321,8 +323,10 @@ _hb_buffer_serialize_glyphs_text (hb_buffer_t *buffer,if (pos && !(flags & HB_BUFFER_SERIALIZE_FLAG_NO_POSITIONS)){- if (x+pos[i].x_offset || y+pos[i].y_offset)- p += hb_max (0, snprintf (p, ARRAY_LENGTH (b) - (p - b), "@%d,%d", x+pos[i].x_offset, y+pos[i].y_offset));+ hb_position_t dx = hb_saturate_add (x, pos[i].x_offset);+ hb_position_t dy = hb_saturate_add (y, pos[i].y_offset);+ if (dx || dy)+ p += hb_max (0, snprintf (p, ARRAY_LENGTH (b) - (p - b), "@%d,%d", dx, dy));if (!(flags & HB_BUFFER_SERIALIZE_FLAG_NO_ADVANCES)){@@ -363,8 +367,8 @@ _hb_buffer_serialize_glyphs_text (hb_buffer_t *buffer,if (pos && (flags & HB_BUFFER_SERIALIZE_FLAG_NO_ADVANCES)){- x += pos[i].x_advance;- y += pos[i].y_advance;+ x = hb_saturate_add (x, pos[i].x_advance);+ y = hb_saturate_add (y, pos[i].y_advance);}}@@ -796,19 +800,19 @@ hb_buffer_deserialize_glyphs (hb_buffer_t *buffer,return false;}- hb_buffer_set_content_type (buffer, HB_BUFFER_CONTENT_TYPE_GLYPHS);-if (!font)font = hb_font_get_empty ();switch (format){case HB_BUFFER_SERIALIZE_FORMAT_TEXT:+ hb_buffer_set_content_type (buffer, HB_BUFFER_CONTENT_TYPE_GLYPHS);return _hb_buffer_deserialize_text_glyphs (buffer,buf, buf_len, end_ptr,font);case HB_BUFFER_SERIALIZE_FORMAT_JSON:+ hb_buffer_set_content_type (buffer, HB_BUFFER_CONTENT_TYPE_GLYPHS);return _hb_buffer_deserialize_json (buffer,buf, buf_len, end_ptr,font);@@ -867,18 +871,18 @@ hb_buffer_deserialize_unicode (hb_buffer_t *buffer,return false;}- hb_buffer_set_content_type (buffer, HB_BUFFER_CONTENT_TYPE_UNICODE);-hb_font_t* font = hb_font_get_empty ();switch (format){case HB_BUFFER_SERIALIZE_FORMAT_TEXT:+ hb_buffer_set_content_type (buffer, HB_BUFFER_CONTENT_TYPE_UNICODE);return _hb_buffer_deserialize_text_unicode (buffer,buf, buf_len, end_ptr,font);case HB_BUFFER_SERIALIZE_FORMAT_JSON:+ hb_buffer_set_content_type (buffer, HB_BUFFER_CONTENT_TYPE_UNICODE);return _hb_buffer_deserialize_json (buffer,buf, buf_len, end_ptr,font);diff --git a/thirdparty/harfbuzz/src/hb-buffer-verify.cc b/thirdparty/harfbuzz/src/hb-buffer-verify.ccindex 4bcdd039838..69c85e991ff 100644--- a/thirdparty/harfbuzz/src/hb-buffer-verify.cc+++ b/thirdparty/harfbuzz/src/hb-buffer-verify.cc@@ -147,7 +147,11 @@ buffer_verify_unsafe_to_break (hb_buffer_t *buffer,text_start--;}}- assert (text_start < text_end);+ if (unlikely (text_start >= text_end))+ {+ buffer_verify_error (buffer, font, BUFFER_VERIFY_ERROR "unsafe-to-break text range is invalid.");+ return false;+ }if (false)printf("start %u end %u text start %u end %u\n", start, end, text_start, text_end);@@ -163,7 +167,7 @@ buffer_verify_unsafe_to_break (hb_buffer_t *buffer,hb_buffer_append (fragment, text_buffer, text_start, text_end);if (!hb_shape_full (font, fragment, features, num_features, shapers) ||- fragment->successful)+ !fragment->successful)return true;hb_buffer_append (reconstruction, fragment, 0, -1);@@ -380,11 +384,14 @@ hb_buffer_t::verify (hb_buffer_t *text_buffer,const char * const *shapers){bool ret = true;- if (!buffer_verify_monotone (this, font))+ bool monotone = buffer_verify_monotone (this, font);+ if (!monotone)ret = false;- if (!buffer_verify_unsafe_to_break (this, text_buffer, font, features, num_features, shapers))+ if (monotone &&+ !buffer_verify_unsafe_to_break (this, text_buffer, font, features, num_features, shapers))ret = false;- if ((flags & HB_BUFFER_FLAG_PRODUCE_UNSAFE_TO_CONCAT) != 0 &&+ if (monotone &&+ (flags & HB_BUFFER_FLAG_PRODUCE_UNSAFE_TO_CONCAT) != 0 &&!buffer_verify_unsafe_to_concat (this, text_buffer, font, features, num_features, shapers))ret = false;if (!ret)diff --git a/thirdparty/harfbuzz/src/hb-buffer.cc b/thirdparty/harfbuzz/src/hb-buffer.ccindex 45d5877bce7..e62abaabd17 100644--- a/thirdparty/harfbuzz/src/hb-buffer.cc+++ b/thirdparty/harfbuzz/src/hb-buffer.cc@@ -484,6 +484,13 @@ hb_buffer_t::move_to (unsigned int i)unsigned int count = i - out_len;if (unlikely (!make_room_for (count, count))) return false;+ max_ops -= count;+ if (unlikely (max_ops < 0))+ {+ successful = false;+ return false;+ }+memmove (out_info + out_len, info + idx, count * sizeof (out_info[0]));idx += count;out_len += count;@@ -504,6 +511,13 @@ hb_buffer_t::move_to (unsigned int i)assert (idx >= count);+ max_ops -= count;+ if (unlikely (max_ops < 0))+ {+ successful = false;+ return false;+ }+idx -= count;out_len -= count;memmove (info + idx, out_info + out_len, count * sizeof (out_info[0]));@@ -2103,18 +2117,18 @@ normalize_glyphs_cluster (hb_buffer_t *buffer,hb_position_t total_x_advance = 0, total_y_advance = 0;for (unsigned int i = start; i < end; i++){- total_x_advance += pos[i].x_advance;- total_y_advance += pos[i].y_advance;+ total_x_advance = hb_saturate_add (total_x_advance, pos[i].x_advance);+ total_y_advance = hb_saturate_add (total_y_advance, pos[i].y_advance);}hb_position_t x_advance = 0, y_advance = 0;for (unsigned int i = start; i < end; i++){- pos[i].x_offset += x_advance;- pos[i].y_offset += y_advance;+ pos[i].x_offset = hb_saturate_add (pos[i].x_offset, x_advance);+ pos[i].y_offset = hb_saturate_add (pos[i].y_offset, y_advance);- x_advance += pos[i].x_advance;- y_advance += pos[i].y_advance;+ x_advance = hb_saturate_add (x_advance, pos[i].x_advance);+ y_advance = hb_saturate_add (y_advance, pos[i].y_advance);pos[i].x_advance = 0;pos[i].y_advance = 0;@@ -2129,11 +2143,11 @@ normalize_glyphs_cluster (hb_buffer_t *buffer,hb_stable_sort (buffer->info + start, end - start - 1, compare_info_codepoint, buffer->pos + start);} else {/* Transfer all cluster advance to the first glyph. */- pos[start].x_advance += total_x_advance;- pos[start].y_advance += total_y_advance;+ pos[start].x_advance = hb_saturate_add (pos[start].x_advance, total_x_advance);+ pos[start].y_advance = hb_saturate_add (pos[start].y_advance, total_y_advance);for (unsigned int i = start + 1; i < end; i++) {- pos[i].x_offset -= total_x_advance;- pos[i].y_offset -= total_y_advance;+ pos[i].x_offset = hb_saturate_sub (pos[i].x_offset, total_x_advance);+ pos[i].y_offset = hb_saturate_sub (pos[i].y_offset, total_y_advance);}hb_stable_sort (buffer->info + start + 1, end - start - 1, compare_info_codepoint, buffer->pos + start + 1);}@@ -2258,15 +2272,20 @@ hb_buffer_diff (hb_buffer_t *buffer,if (buffer->content_type == HB_BUFFER_CONTENT_TYPE_GLYPHS){+ auto position_diff = [] (hb_position_t a, hb_position_t b) -> uint64_t+ {+ int64_t diff = (int64_t) a - b;+ return diff < 0 ? -diff : diff;+ };assert (buffer->have_positions);const hb_glyph_position_t *buf_pos = buffer->pos;const hb_glyph_position_t *ref_pos = reference->pos;for (unsigned int i = 0; i < count; i++){- if ((unsigned int) abs (buf_pos->x_advance - ref_pos->x_advance) > position_fuzz ||- (unsigned int) abs (buf_pos->y_advance - ref_pos->y_advance) > position_fuzz ||- (unsigned int) abs (buf_pos->x_offset - ref_pos->x_offset) > position_fuzz ||- (unsigned int) abs (buf_pos->y_offset - ref_pos->y_offset) > position_fuzz)+ if (position_diff (buf_pos->x_advance, ref_pos->x_advance) > position_fuzz ||+ position_diff (buf_pos->y_advance, ref_pos->y_advance) > position_fuzz ||+ position_diff (buf_pos->x_offset, ref_pos->x_offset) > position_fuzz ||+ position_diff (buf_pos->y_offset, ref_pos->y_offset) > position_fuzz){result |= HB_BUFFER_DIFF_FLAG_POSITION_MISMATCH;break;diff --git a/thirdparty/harfbuzz/src/hb-cairo-utils.cc b/thirdparty/harfbuzz/src/hb-cairo-utils.ccindex f4edc9b16db..9e45f41d0b2 100644--- a/thirdparty/harfbuzz/src/hb-cairo-utils.cc+++ b/thirdparty/harfbuzz/src/hb-cairo-utils.cc@@ -94,6 +94,32 @@ _hb_cairo_destroy_blob (void *p)hb_blob_destroy ((hb_blob_t *) p);}+void+_hb_cairo_set_source_color (hb_cairo_context_t *c,+ hb_bool_t use_foreground,+ hb_color_t color)+{+ cairo_t *cr = c->cr;++ if (use_foreground)+ {+#ifdef HAVE_CAIRO_USER_SCALED_FONT_GET_FOREGROUND_SOURCE+ double r, g, b, a;+ cairo_pattern_t *foreground = cairo_user_scaled_font_get_foreground_source (c->scaled_font);+ if (cairo_pattern_get_rgba (foreground, &r, &g, &b, &a) == CAIRO_STATUS_SUCCESS)+ cairo_set_source_rgba (cr, r, g, b, a * hb_color_get_alpha (color) / 255.);+ else+#endif+ cairo_set_source_rgba (cr, 0, 0, 0, hb_color_get_alpha (color) / 255.);+ }+ else+ cairo_set_source_rgba (cr,+ hb_color_get_red (color) / 255.,+ hb_color_get_green (color) / 255.,+ hb_color_get_blue (color) / 255.,+ hb_color_get_alpha (color) / 255.);+}+hb_bool_t_hb_cairo_paint_glyph_image (hb_cairo_context_t *c,hb_blob_t *blob,@@ -211,7 +237,7 @@ _hb_cairo_get_color_stops (hb_cairo_context_t *c,return false;if (len > *count){- *stops = (hb_color_stop_t *) hb_malloc (len * sizeof (hb_color_stop_t));+ *stops = (hb_color_stop_t *) hb_malloc2 (len, sizeof (hb_color_stop_t));if (unlikely (!*stops))return false;allocated = true;@@ -579,7 +605,7 @@ _hb_cairo_paint_sweep_gradient (hb_cairo_context_t *c,hb_array_t<hb_color_stop_t> (stops, len).qsort ([] (const hb_color_stop_t &a, const hb_color_stop_t &b) {- return a.offset < b.offset;+ return (a.offset > b.offset) - (a.offset < b.offset);});cairo_clip_extents (cr, &x1, &y1, &x2, &y2);diff --git a/thirdparty/harfbuzz/src/hb-cairo-utils.hh b/thirdparty/harfbuzz/src/hb-cairo-utils.hhindex a26bf59d918..c9e3801209e 100644--- a/thirdparty/harfbuzz/src/hb-cairo-utils.hh+++ b/thirdparty/harfbuzz/src/hb-cairo-utils.hh@@ -75,6 +75,11 @@ _hb_paint_composite_mode_to_cairo (hb_paint_composite_mode_t mode)}}+HB_INTERNAL void+_hb_cairo_set_source_color (hb_cairo_context_t *c,+ hb_bool_t use_foreground,+ hb_color_t color);+HB_INTERNAL hb_bool_t_hb_cairo_paint_glyph_image (hb_cairo_context_t *c,hb_blob_t *blob,diff --git a/thirdparty/harfbuzz/src/hb-cairo.cc b/thirdparty/harfbuzz/src/hb-cairo.ccindex ddb5d23dc88..04440c19a7e 100644--- a/thirdparty/harfbuzz/src/hb-cairo.cc+++ b/thirdparty/harfbuzz/src/hb-cairo.cc@@ -166,6 +166,29 @@ hb_cairo_pop_transform (hb_paint_funcs_t *pfuncs HB_UNUSED,cairo_restore (cr);}+static void+hb_cairo_fill_glyph (hb_paint_funcs_t *pfuncs HB_UNUSED,+ void *paint_data,+ hb_codepoint_t glyph,+ hb_font_t *font,+ hb_bool_t use_foreground,+ hb_color_t color,+ void *user_data HB_UNUSED)+{+ hb_cairo_context_t *c = (hb_cairo_context_t *) paint_data;+ cairo_t *cr = c->cr;++ cairo_save (cr);++ cairo_new_path (cr);+ hb_font_draw_glyph (font, glyph, hb_cairo_draw_get_funcs (), cr);+ cairo_close_path (cr);+ _hb_cairo_set_source_color (c, use_foreground, color);+ cairo_fill (cr);++ cairo_restore (cr);+}+static hb_bool_thb_cairo_paint_color_glyph (hb_paint_funcs_t *pfuncs HB_UNUSED,void *paint_data,@@ -303,23 +326,7 @@ hb_cairo_paint_color (hb_paint_funcs_t *pfuncs HB_UNUSED,hb_cairo_context_t *c = (hb_cairo_context_t *) paint_data;cairo_t *cr = c->cr;- if (use_foreground)- {-#ifdef HAVE_CAIRO_USER_SCALED_FONT_GET_FOREGROUND_SOURCE- double r, g, b, a;- cairo_pattern_t *foreground = cairo_user_scaled_font_get_foreground_source (c->scaled_font);- if (cairo_pattern_get_rgba (foreground, &r, &g, &b, &a) == CAIRO_STATUS_SUCCESS)- cairo_set_source_rgba (cr, r, g, b, a * hb_color_get_alpha (color) / 255.);- else-#endif- cairo_set_source_rgba (cr, 0, 0, 0, hb_color_get_alpha (color) / 255.);- }- else- cairo_set_source_rgba (cr,- hb_color_get_red (color) / 255.,- hb_color_get_green (color) / 255.,- hb_color_get_blue (color) / 255.,- hb_color_get_alpha (color) / 255.);+ _hb_cairo_set_source_color (c, use_foreground, color);cairo_paint (cr);}@@ -452,6 +459,7 @@ static struct hb_cairo_paint_funcs_lazy_loader_t : hb_paint_funcs_lazy_loader_t<hb_paint_funcs_set_push_transform_func (funcs, hb_cairo_push_transform, nullptr, nullptr);hb_paint_funcs_set_pop_transform_func (funcs, hb_cairo_pop_transform, nullptr, nullptr);+ hb_paint_funcs_set_fill_glyph_func (funcs, hb_cairo_fill_glyph, nullptr, nullptr);hb_paint_funcs_set_color_glyph_func (funcs, hb_cairo_paint_color_glyph, nullptr, nullptr);hb_paint_funcs_set_push_clip_glyph_func (funcs, hb_cairo_push_clip_glyph, nullptr, nullptr);hb_paint_funcs_set_push_clip_rectangle_func (funcs, hb_cairo_push_clip_rectangle, nullptr, nullptr);@@ -541,8 +549,8 @@ hb_cairo_init_scaled_font (cairo_scaled_font_t *scaled_font,cairo_matrix_t font_matrix;cairo_scaled_font_get_scale_matrix (scaled_font, &font_matrix);hb_font_set_scale (font,- round (font_matrix.xx * scale_factor),- round (font_matrix.yy * scale_factor));+ hb_clamp_to<int32_t> (round (font_matrix.xx * scale_factor)),+ hb_clamp_to<int32_t> (round (font_matrix.yy * scale_factor)));}auto *init_func = (hb_cairo_font_init_func_t)@@ -570,7 +578,7 @@ hb_cairo_init_scaled_font (cairo_scaled_font_t *scaled_font,hb_font_get_h_extents (font, &hb_extents);extents->ascent = (double) hb_extents.ascender / y_scale;- extents->descent = (double) -hb_extents.descender / y_scale;+ extents->descent = -(double) hb_extents.descender / y_scale;extents->height = extents->ascent + extents->descent;#ifdef HAVE_CAIRO_USER_FONT_FACE_SET_RENDER_COLOR_GLYPH_FUNC@@ -675,10 +683,9 @@ hb_cairo_render_color_glyph (cairo_scaled_font_t *scaled_font,c.color_cache = (hb_map_t *) cairo_scaled_font_get_user_data (scaled_font, &color_cache_key);/* Synthesizing variant: mono glyphs render here too via the- * push_clip_glyph + foreground-fill fallback inside- * hb_font_paint_glyph. Callers that want the cheaper- * outline path for mono fonts set CAIRO_COLOR_MODE_NO_COLOR- * on the font options instead. */+ * fill_glyph foreground fallback inside hb_font_paint_glyph.+ * Callers that want the cheaper outline path for mono fonts set+ * CAIRO_COLOR_MODE_NO_COLOR on the font options instead. */hb_font_paint_glyph (font, glyph, hb_cairo_paint_get_funcs (), &c, palette, color);return CAIRO_STATUS_SUCCESS;@@ -1007,15 +1014,15 @@ hb_cairo_glyphs_from_buffer (hb_buffer_t *buffer,double x_scale = x_scale_factor ? 1. / x_scale_factor : 0.;double y_scale = y_scale_factor ? 1. / y_scale_factor : 0.;- hb_position_t hx = 0, hy = 0;+ double hx = 0, hy = 0;int i;for (i = 0; i < (int) *num_glyphs; i++){(*glyphs)[i].index = hb_glyph[i].codepoint;- (*glyphs)[i].x = x + (+hb_position->x_offset + hx) * x_scale;- (*glyphs)[i].y = y + (-hb_position->y_offset + hy) * y_scale;+ (*glyphs)[i].x = x + ((double) hb_position->x_offset + hx) * x_scale;+ (*glyphs)[i].y = y + (-(double) hb_position->y_offset + hy) * y_scale;hx += hb_position->x_advance;- hy += -hb_position->y_advance;+ hy -= hb_position->y_advance;hb_position++;}diff --git a/thirdparty/harfbuzz/src/hb-cff-interp-common.hh b/thirdparty/harfbuzz/src/hb-cff-interp-common.hhindex df90fb99a03..9ca8bf56d92 100644--- a/thirdparty/harfbuzz/src/hb-cff-interp-common.hh+++ b/thirdparty/harfbuzz/src/hb-cff-interp-common.hh@@ -220,16 +220,32 @@ inline unsigned int OpCode_Size (op_code_t op) { return Is_OpCode_ESC (op) ? 2:struct number_t{void set_int (int v) { value = v; }- int to_int () const { return value; }+ bool to_int (int *v) const+ {+ if (unlikely (!(value >= INT_MIN && value <= INT_MAX)))+ {+ *v = 0;+ return false;+ }+ *v = (int) value;+ return true;+ }+ int to_int () const+ {+ int v;+ if (likely (to_int (&v))) return v;+ return value < 0 ? INT_MIN : value > 0 ? INT_MAX : 0;+ }void set_fixed (int32_t v) { value = v / 65536.0; }- int32_t to_fixed () const { return value * 65536.0; }+ int32_t to_fixed () const+ { return (int32_t) hb_clamp (value * 65536.0, (double) INT32_MIN, (double) INT32_MAX); }void set_real (double v) { value = v; }double to_real () const { return value; }bool in_int_range () const- { return ((double) (int16_t) to_int () == value); }+ { return value >= INT16_MIN && value <= INT16_MAX && (double) (int16_t) value == value; }bool operator > (const number_t &n) const { return value > n.to_real (); }bool operator < (const number_t &n) const { return n > *this; }@@ -446,7 +462,13 @@ struct arg_stack_t : cff_stack_t<ARG, 513>ARG& pop_num () { return this->pop (); }- int pop_int () { return this->pop ().to_int (); }+ int pop_int ()+ {+ int v;+ if (unlikely (!this->pop ().to_int (&v)))+ S::set_error ();+ return v;+ }unsigned int pop_uint (){diff --git a/thirdparty/harfbuzz/src/hb-cff-interp-cs-common.hh b/thirdparty/harfbuzz/src/hb-cff-interp-cs-common.hhindex 28a777eb0d4..66884d4a659 100644--- a/thirdparty/harfbuzz/src/hb-cff-interp-cs-common.hh+++ b/thirdparty/harfbuzz/src/hb-cff-interp-cs-common.hh@@ -877,23 +877,26 @@ struct cs_interpreter_t : interpreter_t<ENV>{cs_interpreter_t (ENV& env_) : interpreter_t<ENV> (env_) {}- bool interpret (PARAM& param)+ bool interpret (PARAM& param, int64_t *budget = nullptr){SUPER::env.set_endchar (false);+ bool ret = true;unsigned max_ops = HB_CFF_MAX_OPS;for (;;) {OPSET::process_op (SUPER::env.fetch_op (), SUPER::env, param);if (unlikely (SUPER::env.in_error () || !--max_ops)){SUPER::env.set_error ();- return false;+ ret = false;+ break;}if (SUPER::env.is_endchar ())break;}- return true;+ if (budget) *budget -= (int64_t) (HB_CFF_MAX_OPS - max_ops);+ return ret;}private:diff --git a/thirdparty/harfbuzz/src/hb-cff2-interp-cs.hh b/thirdparty/harfbuzz/src/hb-cff2-interp-cs.hhindex 6a338b462b9..770a4ae36e5 100644--- a/thirdparty/harfbuzz/src/hb-cff2-interp-cs.hh+++ b/thirdparty/harfbuzz/src/hb-cff2-interp-cs.hh@@ -78,7 +78,8 @@ struct cff2_cs_interp_env_t : cs_interp_env_t<ELEM, CFF2Subrs>num_coords = num_coords_;varStore = acc.varStore;do_blend = num_coords && varStore->size;- set_ivs (acc.privateDicts[fd].ivs);+ orig_ivs = acc.privateDicts[fd].ivs;+ set_ivs (orig_ivs);}~cff2_cs_interp_env_t ()@@ -179,6 +180,8 @@ struct cff2_cs_interp_env_t : cs_interp_env_t<ELEM, CFF2Subrs>void set_region_count (unsigned int region_count_) { region_count = region_count_; }unsigned int get_ivs () const { return ivs; }void set_ivs (unsigned int ivs_) { ivs = ivs_; }+ /* The FD's private-dict ivs, before any vsindex op in the charstring. */+ unsigned int get_orig_ivs () const { return orig_ivs; }bool seen_vsindex () const { return seen_vsindex_; }double blend_deltas (hb_array_t<const ELEM> deltas) const@@ -204,6 +207,7 @@ struct cff2_cs_interp_env_t : cs_interp_env_t<ELEM, CFF2Subrs>const CFF2ItemVariationStore *varStore;unsigned int region_count;unsigned int ivs;+ unsigned int orig_ivs;hb_vector_t<float> *scalars = nullptr;hb_atomic_t<hb_vector_t<float> *> *cached_scalars_vector = nullptr;bool do_blend;@@ -260,6 +264,19 @@ struct cff2_cs_opset_t : cs_opset_t<ELEM, OPSET, cff2_cs_interp_env_t<ELEM>, PAR{if (env.have_coords ())arg.set_int (round (arg.to_real () + env.blend_deltas (blends)));+ else if (unlikely (arg.blending ()))+ {+ /* A blend result used as an operand of a later blend: the value is+ * default + inner deltas + outer deltas, so accumulate the deltas. */+ hb_vector_t<number_t> inner = std::move (arg.deltas);+ arg.set_blends (n, i, blends);+ if (likely (inner.length == arg.deltas.length))+ for (unsigned j = 0; j < inner.length; j++)+ arg.deltas.arrayZ[j].set_real (arg.deltas.arrayZ[j].to_real () ++ inner.arrayZ[j].to_real ());+ else+ env.set_error ();+ }elsearg.set_blends (n, i, blends);}diff --git a/thirdparty/harfbuzz/src/hb-config.hh b/thirdparty/harfbuzz/src/hb-config.hhindex 62e0d2022e3..161766fd093 100644--- a/thirdparty/harfbuzz/src/hb-config.hh+++ b/thirdparty/harfbuzz/src/hb-config.hh@@ -38,6 +38,7 @@#ifndef HB_EXPERIMENTAL_API#define HB_NO_BEYOND_64K#define HB_NO_CUBIC_GLYF+#define HB_NO_SUBSET_DEPEND#endif#ifdef HB_TINY@@ -75,9 +76,11 @@#define HB_NO_MMAP#define HB_NO_NAME#define HB_NO_OPEN+#define HB_NO_OT_FETCH#define HB_NO_OT_FONT_GLYPH_NAMES#define HB_NO_SETLOCALE#define HB_NO_STYLE+#define HB_NO_SUBSET_DEPEND#define HB_NO_VERTICAL#define HB_NO_VAR@@ -136,7 +139,7 @@#endif#ifdef HB_NO_DRAW-#define HB_NO_CFF+#define HB_NO_OT_FONT_CFF#define HB_NO_OUTLINE#define HB_NO_PAINT#endif@@ -188,6 +191,13 @@#define HB_NO_OT_FONT_CMAP_CACHE#endif+#if defined(HAVE_CONFIG_OVERRIDE_LAST_H) || defined(HB_CONFIG_OVERRIDE_LAST_H)+#ifndef HB_CONFIG_OVERRIDE_LAST_H+#define HB_CONFIG_OVERRIDE_LAST_H "config-override-last.h"+#endif+#include HB_CONFIG_OVERRIDE_LAST_H+#endif+#ifdef HB_OPTIMIZE_SIZE#define HB_OPTIMIZE_SIZE_VAL 1#elsediff --git a/thirdparty/harfbuzz/src/hb-coretext-font.cc b/thirdparty/harfbuzz/src/hb-coretext-font.ccindex 9f46928275e..9ae3e7764b3 100644--- a/thirdparty/harfbuzz/src/hb-coretext-font.cc+++ b/thirdparty/harfbuzz/src/hb-coretext-font.cc@@ -225,7 +225,8 @@ hb_coretext_get_glyph_h_advances (hb_font_t* font,CTFontGetAdvancesForGlyphs (ct_font, kCTFontOrientationHorizontal, cg_glyph, advances, c);for (unsigned j = 0; j < c; j++){- *first_advance = round (advances[j].width * x_mult) - tracking;+ *first_advance = hb_clamp_to<hb_position_t> (+ round (advances[j].width * x_mult) - (double) tracking);first_advance = &StructAtOffset<hb_position_t> (first_advance, advance_stride);}}@@ -245,7 +246,7 @@ hb_coretext_get_glyph_v_advances (hb_font_t* font,CTFontRef ct_font = (CTFontRef) (const void *) font->data.coretext;CGFloat ct_font_size = CTFontGetSize (ct_font);- CGFloat y_mult = (CGFloat) -font->y_scale / ct_font_size;+ CGFloat y_mult = -(CGFloat) font->y_scale / ct_font_size;hb_position_t tracking = font->face->table.trak->get_tracking (font, HB_DIRECTION_TTB, 0.f);CGGlyph cg_glyph[MAX_GLYPHS];@@ -261,7 +262,8 @@ hb_coretext_get_glyph_v_advances (hb_font_t* font,CTFontGetAdvancesForGlyphs (ct_font, kCTFontOrientationVertical, cg_glyph, advances, c);for (unsigned j = 0; j < c; j++){- *first_advance = round (advances[j].width * y_mult) - tracking;+ *first_advance = hb_clamp_to<hb_position_t> (+ round (advances[j].width * y_mult) - (double) tracking);first_advance = &StructAtOffset<hb_position_t> (first_advance, advance_stride);}}@@ -278,15 +280,15 @@ hb_coretext_get_glyph_v_origin (hb_font_t *font,CTFontRef ct_font = (CTFontRef) (const void *) font->data.coretext;CGFloat ct_font_size = CTFontGetSize (ct_font);- CGFloat x_mult = (CGFloat) -font->x_scale / ct_font_size;- CGFloat y_mult = (CGFloat) -font->y_scale / ct_font_size;+ CGFloat x_mult = -(CGFloat) font->x_scale / ct_font_size;+ CGFloat y_mult = -(CGFloat) font->y_scale / ct_font_size;const CGGlyph glyphs = glyph;CGSize origin;CTFontGetVerticalTranslationsForGlyphs (ct_font, &glyphs, &origin, 1);- *x = round (x_mult * origin.width);- *y = round (y_mult * origin.height);+ *x = hb_clamp_to<hb_position_t> (round (x_mult * origin.width));+ *y = hb_clamp_to<hb_position_t> (round (y_mult * origin.height));return true;}@@ -309,10 +311,12 @@ hb_coretext_get_glyph_extents (hb_font_t *font,CGRect bounds = ::CTFontGetBoundingRectsForGlyphs(ct_font,kCTFontOrientationDefault, glyphs, NULL, 1);- extents->x_bearing = round (bounds.origin.x * x_mult);- extents->y_bearing = round ((bounds.origin.y + bounds.size.height) * y_mult);- extents->width = round (bounds.size.width * x_mult);- extents->height = round (bounds.origin.y * y_mult) - extents->y_bearing;+ double y_bearing = round ((bounds.origin.y + bounds.size.height) * y_mult);++ extents->x_bearing = hb_clamp_to<hb_position_t> (round (bounds.origin.x * x_mult));+ extents->y_bearing = hb_clamp_to<hb_position_t> (y_bearing);+ extents->width = hb_clamp_to<hb_position_t> (round (bounds.size.width * x_mult));+ extents->height = hb_clamp_to<hb_position_t> (round (bounds.origin.y * y_mult) - y_bearing);return true;}@@ -328,9 +332,9 @@ hb_coretext_get_font_h_extents (hb_font_t *font,CGFloat ct_font_size = CTFontGetSize (ct_font);CGFloat y_mult = (CGFloat) font->y_scale / ct_font_size;- metrics->ascender = round (CTFontGetAscent (ct_font) * y_mult);- metrics->descender = -round (CTFontGetDescent (ct_font) * y_mult);- metrics->line_gap = round (CTFontGetLeading (ct_font) * y_mult);+ metrics->ascender = hb_clamp_to<hb_position_t> (round (CTFontGetAscent (ct_font) * y_mult));+ metrics->descender = hb_clamp_to<hb_position_t> (-round (CTFontGetDescent (ct_font) * y_mult));+ metrics->line_gap = hb_clamp_to<hb_position_t> (round (CTFontGetLeading (ct_font) * y_mult));return true;}diff --git a/thirdparty/harfbuzz/src/hb-coretext-shape.cc b/thirdparty/harfbuzz/src/hb-coretext-shape.ccindex 89bf090bba9..48507182553 100644--- a/thirdparty/harfbuzz/src/hb-coretext-shape.cc+++ b/thirdparty/harfbuzz/src/hb-coretext-shape.cc@@ -660,9 +660,9 @@ resize_and_retry:hb_position_t x_advance, y_advance, x_offset, y_offset;hb_font_get_glyph_advance_for_direction (font, notdef, dir, &x_advance, &y_advance);hb_font_get_glyph_origin_for_direction (font, notdef, dir, &x_offset, &y_offset);- hb_position_t advance = x_advance + y_advance;- x_offset = -x_offset;- y_offset = -y_offset;+ hb_position_t advance = hb_saturate_add (x_advance, y_advance);+ x_offset = hb_saturate_neg (x_offset);+ y_offset = hb_saturate_neg (y_offset);unsigned int old_len = buffer->len;for (CFIndex j = range.location; j < range.location + range.length; j++)@@ -760,7 +760,8 @@ resize_and_retry:hb_glyph_info_t *info = run_info;if (HB_DIRECTION_IS_HORIZONTAL (buffer->props.direction)){- hb_position_t x_offset = round ((positions[0].x - advances_so_far) * x_mult);+ hb_position_t x_offset = hb_clamp_to<hb_position_t> (+ round ((positions[0].x - advances_so_far) * x_mult));for (unsigned int j = 0; j < num_glyphs; j++){CGFloat advance;@@ -768,16 +769,17 @@ resize_and_retry:advance = positions[j + 1].x - positions[j].x;else /* last glyph */advance = run_advance - (positions[j].x - positions[0].x);- /* int cast necessary to pass through negative values. */- info->mask = (int) round (advance * x_mult);+ /* Signed cast necessary to pass through negative values. */+ info->mask = (hb_mask_t) hb_clamp_to<int32_t> (round (advance * x_mult));info->var1.i32 = x_offset;- info->var2.i32 = round (positions[j].y * y_mult);+ info->var2.i32 = hb_clamp_to<int32_t> (round (positions[j].y * y_mult));info++;}}else{- hb_position_t y_offset = round ((positions[0].y - advances_so_far) * y_mult);+ hb_position_t y_offset = hb_clamp_to<hb_position_t> (+ round ((positions[0].y - advances_so_far) * y_mult));for (unsigned int j = 0; j < num_glyphs; j++){CGFloat advance;@@ -785,9 +787,9 @@ resize_and_retry:advance = positions[j + 1].y - positions[j].y;else /* last glyph */advance = run_advance - (positions[j].y - positions[0].y);- /* int cast necessary to pass through negative values. */- info->mask = (int) round (advance * y_mult);- info->var1.i32 = round (positions[j].x * x_mult);+ /* Signed cast necessary to pass through negative values. */+ info->mask = (hb_mask_t) hb_clamp_to<int32_t> (round (advance * y_mult));+ info->var1.i32 = hb_clamp_to<int32_t> (round (positions[j].x * x_mult));info->var2.i32 = y_offset;info++;}diff --git a/thirdparty/harfbuzz/src/hb-coretext.cc b/thirdparty/harfbuzz/src/hb-coretext.ccindex 7466c5bc771..e257b8cee4f 100644--- a/thirdparty/harfbuzz/src/hb-coretext.cc+++ b/thirdparty/harfbuzz/src/hb-coretext.cc@@ -107,11 +107,12 @@ _hb_cg_get_table_tags (const hb_face_t *face HB_UNUSED,end_offset = hb_min (end_offset, (unsigned) population);*table_count = end_offset - start_offset;- for (unsigned i = start_offset; i < end_offset; i++)- {- CTFontTableTag tag = (CTFontTableTag)(uintptr_t) CFArrayGetValueAtIndex (arr, i);- table_tags[i - start_offset] = tag;- }+ if (table_tags)+ for (unsigned i = start_offset; i < end_offset; i++)+ {+ CTFontTableTag tag = (CTFontTableTag)(uintptr_t) CFArrayGetValueAtIndex (arr, i);+ table_tags[i - start_offset] = tag;+ }return population;}@@ -446,7 +447,7 @@ hb_coretext_face_create_from_file_or_fail (const char *file_name,* Creates an #hb_face_t face object from the specified* blob and face index.*- * This is similar in functionality to hb_face_create_from_blob_or_fail(),+ * This is similar in functionality to hb_face_create_or_fail(),* but uses the CoreText library for loading the font data.** Return value: (transfer full): The new face object, or `NULL` ifdiff --git a/thirdparty/harfbuzz/src/hb-debug.hh b/thirdparty/harfbuzz/src/hb-debug.hhindex dd7343cd5ec..33307a5202c 100644--- a/thirdparty/harfbuzz/src/hb-debug.hh+++ b/thirdparty/harfbuzz/src/hb-debug.hh@@ -356,6 +356,10 @@ struct hb_no_trace_t {#define HB_DEBUG_KBTS (HB_DEBUG+0)#endif+#ifndef HB_DEBUG_DEPEND+#define HB_DEBUG_DEPEND (HB_DEBUG+0)+#endif+/** With tracing.*/diff --git a/thirdparty/harfbuzz/src/hb-depend-data.hh b/thirdparty/harfbuzz/src/hb-depend-data.hhnew file mode 100644index 00000000000..939e5c73b0a--- /dev/null+++ b/thirdparty/harfbuzz/src/hb-depend-data.hh@@ -0,0 +1,668 @@+/*+ * Copyright © 2024 Adobe, Inc.+ *+ * 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.+ *+ * Adobe Author(s): Skef Iterum+ */++#ifndef HB_DEPEND_DATA_HH+#define HB_DEPEND_DATA_HH++/* This file exists to break include cycles: hb-ot-layout-gsubgpos.hh needs+ * hb_depend_data_builder_t for hb_depend_context_t, but hb-depend.hh pulls+ * in table headers that include hb-ot-layout-gsubgpos.hh. */++#include "hb.hh"++#include "hb-multimap.hh"++/* hb_subset_depend_edge_flags_t is defined in hb-depend.h (public header).+ * We redeclare it here under the same include-guard so internal code that+ * includes hb-depend-data.hh without going through hb-depend.h still gets+ * the type. The definitions must stay in sync. */+#ifndef HB_SUBSET_DEPEND_EDGE_FLAGS_T_DEFINED+#define HB_SUBSET_DEPEND_EDGE_FLAGS_T_DEFINED+typedef enum {+ HB_SUBSET_DEPEND_EDGE_FLAG_NONE = 0x00u,+ HB_SUBSET_DEPEND_EDGE_FLAG_FROM_CONTEXT_POSITION = 0x01u,+ HB_SUBSET_DEPEND_EDGE_FLAG_FROM_NESTED_CONTEXT = 0x02u,+} hb_subset_depend_edge_flags_t;+#endif+/* Apply operator overloads now that hb.hh (and thus hb-algs.hh) is available. */+HB_MARK_AS_FLAG_T (hb_subset_depend_edge_flags_t);++/* High bit of a context-set element marks it as an index into the sets array+ * rather than a raw glyph ID. */+#define HB_DEPEND_CONTEXT_SET_FLAG 0x80000000u++/**+ * hb_depend_edge_t:+ *+ * Internal structure representing a single dependency edge in the graph.+ * Records that glyph A depends on glyph B through a specific OpenType+ * mechanism (table_tag), with additional metadata:+ *+ * - table_tag: Source table (GSUB, glyf, CFF, COLR, MATH)+ * - dependent: Target glyph ID+ * - layout_tag: Feature tag (for GSUB), else 0+ * - ligature_set: Index into sets array for ligature components, else INVALID+ * - context_set: Index into sets array for context requirements, else INVALID+ * - flags: Edge flags (FROM_CONTEXT_POSITION, FROM_NESTED_CONTEXT)+ */+struct hb_depend_edge_t {+ hb_depend_edge_t() = delete;+ hb_depend_edge_t(hb_tag_t table_tag,+ hb_codepoint_t dependent,+ hb_tag_t layout_tag,+ hb_codepoint_t ligature_set,+ hb_codepoint_t context_set,+ hb_subset_depend_edge_flags_t flags = HB_SUBSET_DEPEND_EDGE_FLAG_NONE) : table_tag(table_tag),+ dependent(dependent), layout_tag(layout_tag),+ ligature_set(ligature_set), context_set(context_set),+ flags(flags)+ {}++ bool operator == (const hb_depend_edge_t &o) const+ {+ /* NOTE: flags intentionally excluded from equality comparison.+ * Flags are metadata about how an edge was discovered (e.g.,+ * FROM_CONTEXT_POSITION, FROM_NESTED_CONTEXT), not part of the+ * edge's identity. Multiple discoveries of the same edge via+ * different paths should be treated as duplicates. */+ return table_tag == o.table_tag &&+ dependent == o.dependent &&+ layout_tag == o.layout_tag &&+ ligature_set == o.ligature_set &&+ context_set == o.context_set;+ }++ uint32_t hash () const+ {+ /* FNV-1a hash of all identity fields (excludes flags) */+ uint32_t current = 0x84222325; /* FNV-1a offset basis */+ current = current ^ hb_hash (table_tag);+ current = current * 16777619; /* FNV-1a prime */+ current = current ^ hb_hash (dependent);+ current = current * 16777619;+ current = current ^ hb_hash (layout_tag);+ current = current * 16777619;+ current = current ^ hb_hash (ligature_set);+ current = current * 16777619;+ current = current ^ hb_hash (context_set);+ current = current * 16777619;+ return current;+ }++ hb_tag_t table_tag;+ hb_codepoint_t dependent;+ hb_tag_t layout_tag;+ hb_codepoint_t ligature_set;+ hb_codepoint_t context_set;+ hb_subset_depend_edge_flags_t flags;+};++/**+ * hb_depend_edge_key_t:+ *+ * Key structure for edge deduplication. Combines source glyph with edge record.+ * Uses the record's equality and hash operators for comparison.+ */+struct hb_depend_edge_key_t {+ hb_codepoint_t source;+ hb_depend_edge_t record;++ hb_depend_edge_key_t () : source (0), record (0, 0, 0, HB_CODEPOINT_INVALID, HB_CODEPOINT_INVALID, HB_SUBSET_DEPEND_EDGE_FLAG_NONE) {}++ hb_depend_edge_key_t (hb_codepoint_t source,+ hb_tag_t table_tag,+ hb_tag_t layout_tag,+ hb_codepoint_t dependent,+ hb_codepoint_t ligature_set,+ hb_codepoint_t context_set)+ : source (source),+ record (table_tag, dependent, layout_tag, ligature_set, context_set, HB_SUBSET_DEPEND_EDGE_FLAG_NONE) {}++ bool operator == (const hb_depend_edge_key_t &o) const+ {+ return source == o.source && record == o.record;+ }++ uint32_t hash () const+ {+ /* Combine source hash with record hash */+ uint32_t current = 0x84222325; /* FNV-1a offset basis */+ current = current ^ hb_hash (source);+ current = current * 16777619; /* FNV-1a prime */+ current = current ^ record.hash ();+ current = current * 16777619;+ return current;+ }+};++/**+ * hb_depend_glyph_record_t:+ *+ * Internal structure holding all dependency edges for a single glyph.+ */+struct hb_depend_glyph_record_t {+ hb_vector_t<hb_depend_edge_t> dependencies;+};++/**+ * hb_depend_lookup_revmap_t:+ *+ * Internal structure tracking which features are associated with a lookup.+ * Used during GSUB dependency analysis to record the feature tags that+ * activate each lookup.+ */+struct hb_depend_lookup_revmap_t+{+ hb_depend_lookup_revmap_t () = default;+ explicit hb_depend_lookup_revmap_t (bool full) : full (full) {}+ hb_depend_lookup_revmap_t (const hb_depend_lookup_revmap_t &o) : full(o.full),+ fv_indexes(o.fv_indexes) {}+ hb_depend_lookup_revmap_t (hb_depend_lookup_revmap_t &&o) : full(o.full),+ fv_indexes(std::move(o.fv_indexes)) {}+ hb_depend_lookup_revmap_t& operator = (const hb_depend_lookup_revmap_t &o)+ {+ full = o.full;+ fv_indexes = o.fv_indexes;+ return *this;+ }++ bool full = true;+ hb_set_t fv_indexes;+};++/**+ * hb_depend_data_t:+ *+ * Persistent dependency graph data, retained for the lifetime of hb_subset_depend_t.+ * Contains only what is needed at query time:+ * - glyph_dependencies: Per-glyph edge lists+ * - sets: Ligature and context sets indexed by set ID+ *+ * Constructed via hb_depend_data_builder_t; immutable thereafter.+ */+struct hb_depend_data_t+{+ /* Set storage: vector of heap-allocated sets (both ligature and context sets).+ * Using unique_ptr follows HarfBuzz pattern and provides stable pointers. */+ hb_vector_t<hb::unique_ptr<hb_set_t>> sets;++ hb_vector_t<hb_depend_glyph_record_t> glyph_dependencies;++ const hb_set_t *get_set_from_index (hb_codepoint_t index)+ {+ if (index < sets.length)+ return sets[index].get ();+ return nullptr;+ }++ unsigned int get_glyph_entry_count (hb_codepoint_t gid) const+ {+ if (gid < glyph_dependencies.length)+ return glyph_dependencies[gid].dependencies.length;+ return 0;+ }++ bool get_glyph_entry (hb_codepoint_t gid, unsigned int index,+ hb_tag_t *table_tag, hb_codepoint_t *dependent,+ hb_tag_t *layout_tag, hb_codepoint_t *ligature_set,+ hb_codepoint_t *context_set, uint8_t *flags)+ {+ if (gid < glyph_dependencies.length &&+ index < glyph_dependencies[gid].dependencies.length) {+ auto &d = glyph_dependencies[gid].dependencies[index];+ *table_tag = d.table_tag;+ *dependent = d.dependent;+ *layout_tag = d.layout_tag;+ *ligature_set = d.ligature_set;+ *context_set = d.context_set;+ if (flags) *flags = d.flags;+ return true;+ }+ return false;+ }++ void print ()+ {+ for (unsigned i = 0; i < glyph_dependencies.length; i++) {+ auto &gd = glyph_dependencies[i];+ if (!gd.dependencies.length)+ continue;+ printf ("GID %u:\n", i);+ for (auto &d : gd.dependencies) {+ if (d.table_tag == HB_OT_TAG_GSUB) {+ printf (" layout %c%c%c%c -> %u", HB_UNTAG(d.layout_tag), d.dependent);+ if (d.ligature_set != HB_CODEPOINT_INVALID)+ printf (" (ligature)");+ } else {+ printf (" %c%c%c%c -> %u", HB_UNTAG(d.table_tag), d.dependent);+ }+ printf ("\n");+ }+ }+ }+};++/**+ * hb_depend_data_builder_t:+ *+ * Temporary builder for constructing hb_depend_data_t. Holds all state+ * needed during graph extraction; goes out of scope (and is freed) when+ * construction is complete, leaving only hb_depend_data_t.+ *+ * Temporary state (freed on destruction):+ * - lookup_features: Packed lookup index to feature tag mapping+ * - lookup_feature_offsets: Per-lookup offsets into lookup_features+ * - edge_slots: Compact edge deduplication table+ * - set_to_index: Content-based dependency set deduplication map+ * - free_set_list: Indices of freed sets available for reuse+ * - current_context_set_index: Context requirements for current rule+ * - current_edge_flags: Flags to apply to edges being recorded+ */+struct hb_depend_data_builder_t+{+ hb_depend_data_builder_t (hb_depend_data_t &data_)+ : current_context_set_index (HB_CODEPOINT_INVALID),+ current_edge_flags (HB_SUBSET_DEPEND_EDGE_FLAG_NONE),+ data (data_) {}++ /* Forward to data for use during construction (e.g. from hb_depend_context_t) */+ const hb_set_t *get_set_from_index (hb_codepoint_t index)+ { return data.get_set_from_index (index); }++ /* Discard an unused set that was allocated but had no edges added. */+ void discard_set (hb_codepoint_t set_index)+ {+ if (set_index >= data.sets.length)+ {+ DEBUG_MSG (SUBSET, nullptr, "Attempting to discard invalid set %u (max is %u)",+ set_index, data.sets.length - 1);+ return;+ }+ set_to_index.del (data.sets[set_index].get ());+ data.sets[set_index]->clear ();+ check_success (free_set_list.push_or_fail (set_index));+ }++ hb_codepoint_t new_set (const hb_set_t &set)+ {+ hb_codepoint_t set_index;++ if (free_set_list.length > 0)+ {+ set_index = free_set_list.pop ();+ data.sets[set_index]->set (set);+ if (unlikely (data.sets[set_index]->in_error ()))+ return fail_invalid ();+ }+ else+ {+ set_index = data.sets.length;+ hb_set_t *new_set = hb_set_create ();+ if (unlikely (!new_set))+ return fail_invalid ();+ new_set->set (set);+ if (unlikely (new_set->in_error ()))+ {+ hb_set_destroy (new_set);+ return fail_invalid ();+ }+ if (unlikely (!data.sets.push_or_fail (hb::unique_ptr<hb_set_t> {new_set})))+ return fail_invalid ();+ }++ return set_index;+ }++ /* Find an existing dependency set with the same contents, or create one. */+ hb_codepoint_t find_or_create_set (const hb_set_t &set, bool *created = nullptr)+ {+ hb_codepoint_t *existing_idx = nullptr;+ if (set_to_index.has (&set, &existing_idx))+ {+ if (created) *created = false;+ return *existing_idx;+ }++ hb_codepoint_t new_idx = new_set (set);+ if (unlikely (new_idx == HB_CODEPOINT_INVALID))+ return HB_CODEPOINT_INVALID;++ if (unlikely (!set_to_index.set (data.sets[new_idx].get (), new_idx)))+ return fail_invalid ();+ if (created) *created = true;+ return new_idx;+ }++ hb_codepoint_t find_or_create_context_set (const hb_set_t &set)+ { return find_or_create_set (set); }++ /* Build a context set from context information.+ * Encodes backtrack and lookahead requirements as a flattened set.+ * Returns HB_CODEPOINT_INVALID if no context.+ *+ * To ensure canonical encoding and avoid redundancy:+ * 1. First pass: collect all direct (single-glyph) requirements+ * 2. Second pass: create disjunction sets, subtracting direct requirements+ * 3. Combine: add direct requirements and filtered disjunction references+ */+ hb_codepoint_t build_context_set (const hb_vector_t<hb_set_t> *backtrack_sets,+ const hb_vector_t<hb_set_t> *lookahead_sets)+ {+ if ((!backtrack_sets || backtrack_sets->length == 0) &&+ (!lookahead_sets || lookahead_sets->length == 0))+ return HB_CODEPOINT_INVALID;++ /* First pass: collect all direct (single-glyph) requirements */+ hb_set_t direct_requirements;++ if (backtrack_sets)+ {+ for (const auto &back_set : *backtrack_sets)+ {+ if (back_set.get_population () == 1)+ direct_requirements.add (back_set.get_min ());+ }+ }++ if (lookahead_sets)+ {+ for (const auto &look_set : *lookahead_sets)+ {+ if (look_set.get_population () == 1)+ direct_requirements.add (look_set.get_min ());+ }+ }++ /* Second pass: create disjunction sets, filtering out direct requirements */+ hb_set_t context_elements;++ if (backtrack_sets)+ {+ for (const auto &back_set : *backtrack_sets)+ {+ if (back_set.get_population () > 1)+ {+ hb_set_t filtered_set;+ filtered_set.set (back_set);+ filtered_set.subtract (direct_requirements);+ if (unlikely (filtered_set.in_error ()))+ return fail_invalid ();++ if (!filtered_set.is_empty ())+ {+ hb_codepoint_t set_idx = find_or_create_context_set (filtered_set);+ if (unlikely (set_idx == HB_CODEPOINT_INVALID))+ return HB_CODEPOINT_INVALID;+ context_elements.add (HB_DEPEND_CONTEXT_SET_FLAG | set_idx);+ }+ }+ }+ }++ if (lookahead_sets)+ {+ for (const auto &look_set : *lookahead_sets)+ {+ if (look_set.get_population () > 1)+ {+ hb_set_t filtered_set;+ filtered_set.set (look_set);+ filtered_set.subtract (direct_requirements);+ if (unlikely (filtered_set.in_error ()))+ return fail_invalid ();++ if (!filtered_set.is_empty ())+ {+ hb_codepoint_t set_idx = find_or_create_context_set (filtered_set);+ if (unlikely (set_idx == HB_CODEPOINT_INVALID))+ return HB_CODEPOINT_INVALID;+ context_elements.add (HB_DEPEND_CONTEXT_SET_FLAG | set_idx);+ }+ }+ }+ }++ context_elements.union_ (direct_requirements);+ if (unlikely (direct_requirements.in_error () ||+ context_elements.in_error ()))+ return fail_invalid ();++ if (context_elements.is_empty ())+ return HB_CODEPOINT_INVALID;++ return find_or_create_context_set (context_elements);+ }++ static uint64_t encode_edge_ref (hb_codepoint_t source, unsigned int index)+ { return (uint64_t (source) + 1) << 32 | index; }++ static void decode_edge_ref (uint64_t ref,+ hb_codepoint_t *source,+ unsigned int *index)+ {+ *source = (ref >> 32) - 1;+ *index = ref;+ }++ uint32_t edge_hash (hb_codepoint_t source, const hb_depend_edge_t &record) const+ {+ hb_depend_edge_key_t key (source, record.table_tag, record.layout_tag,+ record.dependent, record.ligature_set,+ record.context_set);+ return key.hash ();+ }++ bool resize_edge_slots ()+ {+ unsigned int new_size = edge_slots.length ? edge_slots.length * 2 : 8;+ if (unlikely (new_size < edge_slots.length))+ return fail ();++ hb_vector_t<uint64_t> new_slots;+ if (unlikely (!new_slots.resize_exact (new_size)))+ return fail ();++ for (uint64_t ref : edge_slots)+ {+ if (!ref)+ continue;++ hb_codepoint_t source;+ unsigned int index;+ decode_edge_ref (ref, &source, &index);+ const hb_depend_edge_t &record = data.glyph_dependencies[source].dependencies[index];+ unsigned int slot = edge_hash (source, record) & (new_size - 1);+ unsigned int step = 0;+ while (new_slots[slot])+ slot = (slot + ++step) & (new_size - 1);+ new_slots[slot] = ref;+ }++ edge_slots = std::move (new_slots);+ return true;+ }++ bool add_edge (hb_codepoint_t source, const hb_depend_edge_t &record)+ {+ /* Store only a source and per-glyph edge index in each bucket. The edge+ * itself already lives in the output vector, where it can be compared to+ * resolve hash collisions exactly. Adding one to the encoded source+ * reserves zero as the empty-bucket value. */+ if (unlikely (!edge_slots.length ||+ uint64_t (edge_population) * 3 / 2 >= edge_slots.length - 1))+ if (unlikely (!resize_edge_slots ()))+ return false;++ unsigned int slot = edge_hash (source, record) & (edge_slots.length - 1);+ unsigned int step = 0;+ while (uint64_t ref = edge_slots[slot])+ {+ hb_codepoint_t existing_source;+ unsigned int existing_index;+ decode_edge_ref (ref, &existing_source, &existing_index);+ if (existing_source == source &&+ data.glyph_dependencies[source].dependencies[existing_index] == record)+ return false;+ slot = (slot + ++step) & (edge_slots.length - 1);+ }++ auto &dependencies = data.glyph_dependencies[source].dependencies;+ unsigned int index = dependencies.length;+ if (unlikely (!dependencies.push_or_fail (record)))+ return fail ();++ edge_slots[slot] = encode_edge_ref (source, index);+ edge_population++;+ return true;+ }++ bool add_depend_layout (hb_codepoint_t target, hb_tag_t table_tag,+ hb_tag_t layout_tag,+ hb_codepoint_t dependent,+ hb_codepoint_t lig_set = HB_CODEPOINT_INVALID,+ hb_codepoint_t context_set = HB_CODEPOINT_INVALID,+ hb_subset_depend_edge_flags_t flags = HB_SUBSET_DEPEND_EDGE_FLAG_NONE)+ {+ if (target >= data.glyph_dependencies.length) {+ DEBUG_MSG (SUBSET, nullptr, "Dependency glyph %u for %c%c%c%c too large",+ target, HB_UNTAG(table_tag));+ return false;+ }++ return add_edge (target, hb_depend_edge_t (table_tag, dependent, layout_tag,+ lig_set, context_set, flags));+ }++ bool add_gsub_lookup (hb_codepoint_t target, hb_codepoint_t lookup_index,+ hb_codepoint_t dependent,+ hb_codepoint_t lig_set = HB_CODEPOINT_INVALID,+ hb_codepoint_t context_set = HB_CODEPOINT_INVALID)+ {+ if (context_set == HB_CODEPOINT_INVALID)+ context_set = current_context_set_index;+ hb_subset_depend_edge_flags_t flags = current_edge_flags;++ bool any_added = false;+ for (uint64_t entry : get_lookup_features (lookup_index)) {+ hb_tag_t t = (hb_tag_t) entry;+ if (add_depend_layout (target, HB_OT_TAG_GSUB, t, dependent, lig_set, context_set, flags))+ any_added = true;+ }+ return any_added;+ }++ bool init_lookup_features (unsigned lookup_count)+ {+ return check_success (lookup_feature_offsets.resize (lookup_count + 1));+ }++ bool add_lookup_feature (hb_codepoint_t lookup_index, hb_tag_t feature_tag)+ {+ if (feature_tag == HB_SET_VALUE_INVALID)+ return true;++ if (unlikely (!lookup_feature_offsets.length ||+ lookup_index >= lookup_feature_offsets.length - 1))+ return fail ();++ uint64_t entry = ((uint64_t) lookup_index << 32) | feature_tag;+ return check_success (lookup_features.push_or_fail (entry));+ }++ bool finish_lookup_features ()+ {+ lookup_features.qsort ([] (uint64_t a, uint64_t b) {+ return a < b ? -1 : a > b ? 1 : 0;+ });++ unsigned write = 0;+ for (uint64_t entry : lookup_features)+ if (!write || entry != lookup_features[write - 1])+ lookup_features[write++] = entry;+ lookup_features.shrink (write, false);++ unsigned feature_index = 0;+ unsigned lookup_count = lookup_feature_offsets.length - 1;+ for (unsigned lookup_index = 0; lookup_index < lookup_count; lookup_index++)+ {+ lookup_feature_offsets[lookup_index] = feature_index;+ while (feature_index < lookup_features.length &&+ lookup_features[feature_index] >> 32 == lookup_index)+ feature_index++;+ }+ lookup_feature_offsets[lookup_count] = feature_index;+ return true;+ }++ hb_array_t<const uint64_t> get_lookup_features (hb_codepoint_t lookup_index) const+ {+ if (unlikely (!lookup_feature_offsets.length ||+ lookup_index >= lookup_feature_offsets.length - 1))+ return {};++ unsigned start = lookup_feature_offsets[lookup_index];+ unsigned end = lookup_feature_offsets[lookup_index + 1];+ return lookup_features.as_array ().sub_array (start, end - start);+ }++ void add_depend (hb_codepoint_t target, hb_tag_t table_tag,+ hb_codepoint_t dependent,+ hb_codepoint_t lig_set = HB_CODEPOINT_INVALID,+ hb_codepoint_t context_set = HB_CODEPOINT_INVALID,+ hb_subset_depend_edge_flags_t flags = HB_SUBSET_DEPEND_EDGE_FLAG_NONE)+ {+ add_depend_layout (target, table_tag, HB_CODEPOINT_INVALID, dependent, lig_set,+ context_set, flags);+ }++ hb_codepoint_t get_nominal_glyph (hb_codepoint_t cp)+ { return hb_map_get (&nominal_glyphs, cp); }++ HB_INTERNAL bool compile (hb_face_t *face);++ bool fail () { successful = false; return false; }+ hb_codepoint_t fail_invalid () { fail (); return HB_CODEPOINT_INVALID; }+ bool check_success (bool s) { successful = (successful && s); return successful; }++ HB_INTERNAL void get_gsub_dependencies (hb_face_t *face);++ bool successful = true;+ hb_set_t unicodes;+ hb_map_t nominal_glyphs;+ hb_vector_t<uint64_t> lookup_features;+ hb_vector_t<unsigned> lookup_feature_offsets;+ hb_vector_t<uint64_t> edge_slots;+ unsigned int edge_population = 0;+ hb_hashmap_t<const hb_set_t*, hb_codepoint_t> set_to_index;+ hb_vector_t<hb_codepoint_t> free_set_list;+ hb_codepoint_t current_context_set_index;+ hb_subset_depend_edge_flags_t current_edge_flags;++ hb_depend_data_t &data;+};+++#endif /* HB_DEPEND_DATA_HH */diff --git a/thirdparty/harfbuzz/src/hb-depend.cc b/thirdparty/harfbuzz/src/hb-depend.ccnew file mode 100644index 00000000000..4a78b438778--- /dev/null+++ b/thirdparty/harfbuzz/src/hb-depend.cc@@ -0,0 +1,256 @@+/*+ * Copyright © 2024 Adobe, Inc.+ *+ * 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.+ *+ * Adobe Author(s): Skef Iterum+ */++#include "hb.hh"++#include "hb-depend.hh"++#include "hb-face.hh"+#include "hb-ot-cmap-table.hh"+#include "hb-ot-glyf-table.hh"+#include "hb-ot-layout-gsub-table.hh"+#include "hb-ot-math-table.hh"+#include "hb-ot-cff1-table.hh"+#include "OT/Color/COLR/COLR.hh"+#include "OT/Color/COLR/colrv1-depend.hh"++/**+ * SECTION:hb-subset-depend+ * @title: hb-subset-depend+ * @short_description: Glyph dependency graph for font optimization+ * @include: hb-subset-depend.h+ *+ * <warning>This API is highly experimental and subject to change. It is not+ * enabled by default and should not be used in production code without+ * understanding the stability implications.</warning>+ *+ * Functions for extracting a glyph dependency graph.+ *+ * A dependency graph represents the relationships between glyphs in a font,+ * tracking which glyphs reference or produce other glyphs through OpenType+ * mechanisms such as character mapping, glyph substitution, composite+ * construction, color layering, and math variants.+ *+ * Dependency graphs enable finding all glyphs reachable from a given input set.+ * This is useful for font subsetting, analyzing glyph coverage, optimizing+ * font delivery, and determining which glyphs are needed to render specific+ * characters.+ */++hb_subset_depend_t::hb_subset_depend_t (hb_face_t *f)+{+ if (unlikely (!data.glyph_dependencies.resize_exact (f->get_num_glyphs ()))) {+ successful = false;+ return;+ }+ successful = hb_depend_data_builder_t (data).compile (f);+}++bool+hb_depend_data_builder_t::compile (hb_face_t *face)+{+ /* Extract dependencies from all relevant OpenType tables.+ * Note: cmap (UVS) dependencies are not extracted - UVS closure is handled+ * separately via hb_font_get_variation_glyph() query API during closure+ * computation.+ *+ * For GSUB, hb_ot_layout_has_substitution() forces lazy-loader initialization+ * in libharfbuzz, after which get_relaxed() safely returns the already-+ * constructed accelerator without instantiating the GSUB_accelerator_t+ * constructor (which references a hidden is_blocklisted symbol) in this TU. */+ if (hb_ot_layout_has_substitution (face))+ face->table.GSUB.get_relaxed ()->depend (this, face);+#ifndef HB_NO_MATH+ face->table.MATH->depend (this);+#endif+#ifndef HB_NO_COLOR+ face->table.COLR->depend (this);+#endif+ face->table.glyf->depend (this);+#ifndef HB_NO_CFF+ OT::cff1_subset_accelerator_t (face).depend (this);+#endif+ /* XXX TODO: add face->table.VARC->depend (this) here.+ * VARC closure and subsetting are not yet implemented (see hb-subset-plan.cc),+ * so the right traversal architecture for VarComponent records hasn't been+ * established. Implement VARC depend() in the same commit that adds VARC+ * closure, so both share the same traversal model. Component conditions should+ * be treated as over-approximations (include all components regardless of+ * condition), consistent with how FeatureVariations edges are handled. */+ return successful;+}+++#ifndef HB_NO_SUBSET_DEPEND++/**+ * hb_subset_depend_from_face_or_fail:+ * @face: font face to collect dependencies from+ *+ * Calculates the dependencies between glyphs in the supplied face.+ * Extracts dependency information from GSUB, glyf, CFF, COLR,+ * and MATH tables. UVS (Unicode Variation Sequence) dependencies+ * are not included; handle those via hb_font_get_variation_glyph().+ *+ * Example:+ * ```c+ * hb_subset_depend_t *depend = hb_subset_depend_from_face_or_fail (face);+ * if (!depend) {+ * // Handle error (OOM or invalid face)+ * return;+ * }+ * // ... use depend ...+ * hb_subset_depend_destroy (depend);+ * ```+ *+ * Return value: (transfer full): New depend object, or `nullptr` if creation+ * failed (out of memory or invalid face). Destroy with hb_subset_depend_destroy().+ *+ * Since: 14.3.0+ **/+hb_subset_depend_t *+hb_subset_depend_from_face_or_fail (hb_face_t *face)+{+ hb_subset_depend_t *depend;+ if (unlikely (!(depend = hb_object_create<hb_subset_depend_t> (face))))+ return nullptr;++ if (unlikely (depend->in_error ()))+ {+ hb_subset_depend_destroy (depend);+ return nullptr;+ }++ return depend;+}++/**+ * hb_subset_depend_lookup_glyph:+ * @depend: depend object+ * @gid: GID to retrieve dependencies from+ * @start_offset: offset of first entry to retrieve+ * @entry_count: (inout) (optional): Input = number of entries to fill; output = number+ * actually filled. Pass NULL to query total count without filling.+ * @entries: (out) (optional) (array length=entry_count): Array to fill with dependency+ * edge data. May be NULL if @entry_count is also NULL.+ *+ * Retrieve dependency edges for a glyph. Follows the standard HarfBuzz array-getter+ * pattern: always returns the total number of edges for @gid regardless of+ * @start_offset or @entry_count.+ *+ * Example (iterate all entries):+ * ```c+ * unsigned int total = hb_subset_depend_lookup_glyph (depend, gid, 0, NULL, NULL);+ * for (unsigned int i = 0; i < total; i++) {+ * hb_subset_depend_entry_t entry;+ * unsigned int count = 1;+ * hb_subset_depend_lookup_glyph (depend, gid, i, &count, &entry);+ * // Process entry.table_tag, entry.dependent, etc.+ * }+ * ```+ *+ * Return value: Total number of dependency edges for @gid.+ *+ * Since: 14.3.0+ **/+unsigned int+hb_subset_depend_lookup_glyph (hb_subset_depend_t *depend,+ hb_codepoint_t gid,+ unsigned int start_offset,+ unsigned int *entry_count,+ hb_subset_depend_entry_t *entries)+{+ unsigned int total = depend->data.get_glyph_entry_count (gid);+ if (entry_count)+ {+ unsigned int count = hb_min (*entry_count,+ start_offset < total ? total - start_offset : 0u);+ for (unsigned int i = 0; i < count; i++)+ {+ uint8_t flags_byte = 0;+ depend->data.get_glyph_entry (gid, start_offset + i,+ &entries[i].table_tag, &entries[i].dependent,+ &entries[i].layout_tag, &entries[i].ligature_set_index,+ &entries[i].context_set_index,+ &flags_byte);+ entries[i].flags = (hb_subset_depend_edge_flags_t) flags_byte;+ }+ *entry_count = count;+ }+ return total;+}++/**+ * hb_subset_depend_lookup_set:+ * @depend: depend object+ * @index: the index of the set+ * @out: (out): A pointer to a set to copy into+ *+ * Get all glyphs in a set identified by @index.+ * The set index comes from the ligature_set_index or context_set_index field+ * returned by hb_subset_depend_lookup_glyph().+ *+ * Example:+ * ```c+ * hb_set_t *ligature_glyphs = hb_set_create ();+ * if (hb_subset_depend_lookup_set (depend, entry.ligature_set_index, ligature_glyphs)) {+ * // Process glyphs in the set...+ * }+ * hb_set_destroy (ligature_glyphs);+ * ```+ *+ * Return value: true if there is such a set, false otherwise+ *+ * Since: 14.3.0+ **/+hb_bool_t+hb_subset_depend_lookup_set (hb_subset_depend_t *depend, hb_codepoint_t index,+ hb_set_t *out)+{+ const hb_set_t *s = depend->get_set_from_index (index);+ if (!s) return false;+ out->set (*s);+ return true;+}++/**+ * hb_subset_depend_destroy:+ * @depend: a #hb_subset_depend_t+ *+ * Decreases the reference count on @depend, and if it reaches zero, destroys+ * @depend, freeing all memory.+ *+ * Since: 14.3.0+ **/+void+hb_subset_depend_destroy (hb_subset_depend_t *depend)+{+ if (!hb_object_destroy (depend)) return;++ hb_free (depend);+}++#endif /* !HB_NO_SUBSET_DEPEND */diff --git a/thirdparty/harfbuzz/src/hb-depend.hh b/thirdparty/harfbuzz/src/hb-depend.hhnew file mode 100644index 00000000000..e5ce38aa196--- /dev/null+++ b/thirdparty/harfbuzz/src/hb-depend.hh@@ -0,0 +1,64 @@+/*+ * Copyright © 2024 Adobe, Inc.+ *+ * 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.+ *+ * Adobe Author(s): Skef Iterum+ */++#ifndef HB_DEPEND_HH+#define HB_DEPEND_HH++#include "hb.hh"++#include "hb-subset-depend.h"+#include "hb-depend-data.hh"+++/**+ * hb_subset_depend_t:+ *+ * Internal structure implementing the dependency graph API.+ *+ * Initialized via hb_subset_depend_from_face_or_fail() which computes the dependency+ * graph once via hb_depend_data_builder_t::compile(). The graph remains+ * immutable for the lifetime of the object.+ */+struct hb_subset_depend_t+{+ HB_INTERNAL hb_subset_depend_t (hb_face_t *face);++ hb_object_header_t header;++ bool successful;++ bool in_error () const { return !successful; }++ const hb_set_t *get_set_from_index (hb_codepoint_t index)+ {+ return data.get_set_from_index (index);+ }++ hb_depend_data_t data;+};+++#endif /* HB_DEPEND_HH */diff --git a/thirdparty/harfbuzz/src/hb-directwrite-font.cc b/thirdparty/harfbuzz/src/hb-directwrite-font.ccindex 2ebda19bfc3..854fa9f4daf 100644--- a/thirdparty/harfbuzz/src/hb-directwrite-font.cc+++ b/thirdparty/harfbuzz/src/hb-directwrite-font.cc@@ -38,6 +38,22 @@#define MAX_GLYPHS 256u+static hb_position_t+hb_directwrite_scale_x (hb_font_t *font, int64_t value)+{+ if (value >= INT16_MIN && value <= INT16_MAX)+ return font->em_scale_x ((int16_t) value);+ return font->em_scalef_x ((float) value);+}++static hb_position_t+hb_directwrite_scale_y (hb_font_t *font, int64_t value)+{+ if (value >= INT16_MIN && value <= INT16_MAX)+ return font->em_scale_y ((int16_t) value);+ return font->em_scalef_y ((float) value);+}+static unsigned inthb_directwrite_get_nominal_glyphs (hb_font_t *font,void *font_data HB_UNUSED,@@ -91,9 +107,9 @@ hb_directwrite_get_font_h_extents (hb_font_t *font,DWRITE_FONT_METRICS dw_metrics;dw_face->GetMetrics (&dw_metrics);- metrics->ascender = font->em_scale_y (dw_metrics.ascent);- metrics->descender = -font->em_scale_y (dw_metrics.descent);- metrics->line_gap = font->em_scale_y (dw_metrics.lineGap);+ metrics->ascender = hb_directwrite_scale_y (font, dw_metrics.ascent);+ metrics->descender = hb_saturate_neg (hb_directwrite_scale_y (font, dw_metrics.descent));+ metrics->line_gap = hb_directwrite_scale_y (font, dw_metrics.lineGap);return true;}@@ -134,7 +150,7 @@ hb_directwrite_get_glyph_h_advances (hb_font_t* font,{// https://github.com/harfbuzz/harfbuzz/issues/5319auto advance = gids[j] < num_glyphs ? advances[j] : 0;- *first_advance = font->em_scale_x (advance);+ *first_advance = hb_directwrite_scale_x (font, advance);first_advance = &StructAtOffset<hb_position_t> (first_advance, advance_stride);}@@ -176,7 +192,7 @@ hb_directwrite_get_glyph_v_advances (hb_font_t* font,dw_face1->GetDesignGlyphAdvances (n, gids, advances, true);for (unsigned j = 0; j < n; j++){- *first_advance = -font->em_scale_y (advances[j]);+ *first_advance = hb_saturate_neg (hb_directwrite_scale_y (font, advances[j]));first_advance = &StructAtOffset<hb_position_t> (first_advance, advance_stride);}@@ -200,8 +216,8 @@ hb_directwrite_get_glyph_v_origin (hb_font_t *font,if (FAILED (dw_face->GetDesignGlyphMetrics (&gid, 1, &metrics)))return false;- *x = font->em_scale_x (metrics.advanceWidth / 2);- *y = font->em_scale_y (metrics.verticalOriginY); // Untested+ *x = hb_directwrite_scale_x (font, metrics.advanceWidth / 2);+ *y = hb_directwrite_scale_y (font, metrics.verticalOriginY); // Untestedreturn true;}@@ -222,10 +238,15 @@ hb_directwrite_get_glyph_extents (hb_font_t *font,if (FAILED (dw_face->GetDesignGlyphMetrics (&gid, 1, &metrics)))return false;- extents->x_bearing = font->em_scale_x (metrics.leftSideBearing);- extents->y_bearing = font->em_scale_y (metrics.verticalOriginY - metrics.topSideBearing);- extents->width = font->em_scale_x (metrics.advanceWidth - metrics.rightSideBearing) - extents->x_bearing;- extents->height = font->em_scale_y (metrics.verticalOriginY - metrics.advanceHeight + metrics.bottomSideBearing) - extents->y_bearing; // Magic+ int64_t right = (int64_t) metrics.advanceWidth - metrics.rightSideBearing;+ int64_t top = (int64_t) metrics.verticalOriginY - metrics.topSideBearing;+ int64_t bottom = (int64_t) metrics.verticalOriginY - metrics.advanceHeight + metrics.bottomSideBearing;++ extents->x_bearing = hb_directwrite_scale_x (font, metrics.leftSideBearing);+ extents->y_bearing = hb_directwrite_scale_y (font, top);+ extents->width = hb_saturate_sub (hb_directwrite_scale_x (font, right), extents->x_bearing);+ extents->height = hb_saturate_sub (hb_directwrite_scale_y (font, bottom),+ extents->y_bearing); // Magicreturn true;}@@ -244,8 +265,6 @@ public:void *draw_data): font (font), drawing ({draw_funcs, draw_data}) {}- virtual ~GeometrySink() {}-HRESULT STDMETHODCALLTYPE Close() override { return S_OK; }void STDMETHODCALLTYPE SetFillMode(D2D1_FILL_MODE) override {}void STDMETHODCALLTYPE SetSegmentFlags(D2D1_PATH_SEGMENT) override {}@@ -256,21 +275,21 @@ public:void STDMETHODCALLTYPE BeginFigure(D2D1_POINT_2F startPoint, D2D1_FIGURE_BEGIN) override{- drawing.move_to (font->em_scalef_x (startPoint.x), -font->em_scalef_y (startPoint.y));+ drawing.move_to (font->em_scalef_x (startPoint.x), -(float) font->em_scalef_y (startPoint.y));}void STDMETHODCALLTYPE AddBeziers(const D2D1_BEZIER_SEGMENT *beziers, UINT beziersCount) override{for (unsigned i = 0; i < beziersCount; ++i)- drawing.cubic_to (font->em_scalef_x (beziers[i].point1.x), -font->em_scalef_y (beziers[i].point1.y),- font->em_scalef_x (beziers[i].point2.x), -font->em_scalef_y (beziers[i].point2.y),- font->em_scalef_x (beziers[i].point3.x), -font->em_scalef_y (beziers[i].point3.y));+ drawing.cubic_to (font->em_scalef_x (beziers[i].point1.x), -(float) font->em_scalef_y (beziers[i].point1.y),+ font->em_scalef_x (beziers[i].point2.x), -(float) font->em_scalef_y (beziers[i].point2.y),+ font->em_scalef_x (beziers[i].point3.x), -(float) font->em_scalef_y (beziers[i].point3.y));}void STDMETHODCALLTYPE AddLines(const D2D1_POINT_2F *points, UINT pointsCount) override{for (unsigned i = 0; i < pointsCount; ++i)- drawing.line_to (font->em_scalef_x (points[i].x), -font->em_scalef_y (points[i].y));+ drawing.line_to (font->em_scalef_x (points[i].x), -(float) font->em_scalef_y (points[i].y));}void STDMETHODCALLTYPE EndFigure(D2D1_FIGURE_END) overridediff --git a/thirdparty/harfbuzz/src/hb-directwrite-shape.cc b/thirdparty/harfbuzz/src/hb-directwrite-shape.ccindex 94440686564..8532483beba 100644--- a/thirdparty/harfbuzz/src/hb-directwrite-shape.cc+++ b/thirdparty/harfbuzz/src/hb-directwrite-shape.cc@@ -130,7 +130,6 @@ public:assert (refCount >= 0);if (refCount)return refCount;- delete this;return 0;}@@ -164,14 +163,14 @@ public:{mRefCount.init ();}- virtual ~TextAnalysis ()+ ~TextAnalysis (){- // delete runs, except mRunHead which is part of the TextAnalysis object+ // free runs, except mRunHead which is part of the TextAnalysis objectfor (Run *run = mRunHead.nextRun; run;){Run *origRun = run;run = run->nextRun;- delete origRun;+ hb_free (origRun);}}@@ -266,10 +265,13 @@ public:DWRITE_SCRIPT_ANALYSIS const* scriptAnalysis){SetCurrentRun (textPosition);- SplitCurrentRun (textPosition);+ if (unlikely (!SplitCurrentRun (textPosition)))+ return E_OUTOFMEMORY;while (textLength > 0){Run *run = FetchNextRun (&textLength);+ if (unlikely (!run))+ return E_OUTOFMEMORY;run->mScript = *scriptAnalysis;}@@ -302,7 +304,10 @@ protected:// Split the tail if needed (the length remaining is less than the// current run's size).if (*textLength < mCurrentRun->mTextLength)- SplitCurrentRun (mCurrentRun->mTextStart + *textLength);+ {+ if (unlikely (!SplitCurrentRun (mCurrentRun->mTextStart + *textLength)))+ return nullptr;+ }else// Just advance the current run.mCurrentRun = mCurrentRun->nextRun;@@ -331,22 +336,24 @@ protected:assert (0); // We should always be able to find the text position in one of our runs}- void SplitCurrentRun (uint32_t splitPosition)+ bool SplitCurrentRun (uint32_t splitPosition){if (!mCurrentRun){assert (0); // SplitCurrentRun called without current run// Shouldn't be calling this when no current run is set!- return;+ return false;}// Split the current run.if (splitPosition <= mCurrentRun->mTextStart){// No need to split, already the start of a run// or before it. Usually the first.- return;+ return true;}- Run *newRun = new Run;+ Run *newRun = (Run *) hb_malloc (sizeof (Run));+ if (unlikely (!newRun))+ return false;*newRun = *mCurrentRun;@@ -360,6 +367,7 @@ protected:newRun->mTextLength -= splitPoint;mCurrentRun->mTextLength = splitPoint;mCurrentRun = newRun;+ return true;}protected:@@ -503,15 +511,19 @@ _hb_directwrite_shape (hb_shape_plan_t *shape_plan,}}- uint16_t* clusterMap;- clusterMap = new uint16_t[textLength];- DWRITE_SHAPING_TEXT_PROPERTIES* textProperties;- textProperties = new DWRITE_SHAPING_TEXT_PROPERTIES[textLength];+ hb_vector_t<uint16_t> clusterMap;+ hb_vector_t<DWRITE_SHAPING_TEXT_PROPERTIES> textProperties;+ if (unlikely (!clusterMap.resize_exact (textLength) ||+ !textProperties.resize_exact (textLength)))+ FAIL ("Failed to allocate shaping text data.");++ hb_vector_t<uint16_t> glyphIndices;+ hb_vector_t<DWRITE_SHAPING_GLYPH_PROPERTIES> glyphProperties;retry_getglyphs:- uint16_t* glyphIndices = new uint16_t[maxGlyphCount];- DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProperties;- glyphProperties = new DWRITE_SHAPING_GLYPH_PROPERTIES[maxGlyphCount];+ if (unlikely (!glyphIndices.resize_exact (maxGlyphCount) ||+ !glyphProperties.resize_exact (maxGlyphCount)))+ FAIL ("Failed to allocate shaping glyph data.");hr = analyzer->GetGlyphs (textString,chars_len,@@ -525,17 +537,14 @@ retry_getglyphs:range_char_counts.arrayZ,range_features.length,maxGlyphCount,- clusterMap,- textProperties,- glyphIndices,- glyphProperties,+ clusterMap.arrayZ,+ textProperties.arrayZ,+ glyphIndices.arrayZ,+ glyphProperties.arrayZ,&glyphCount);if (unlikely (hr == HRESULT_FROM_WIN32 (ERROR_INSUFFICIENT_BUFFER))){- delete [] glyphIndices;- delete [] glyphProperties;-maxGlyphCount *= 2;goto retry_getglyphs;@@ -543,8 +552,11 @@ retry_getglyphs:if (FAILED (hr))FAIL ("Analyzer failed to get glyphs.");- float* glyphAdvances = new float[maxGlyphCount];- DWRITE_GLYPH_OFFSET* glyphOffsets = new DWRITE_GLYPH_OFFSET[maxGlyphCount];+ hb_vector_t<float> glyphAdvances;+ hb_vector_t<DWRITE_GLYPH_OFFSET> glyphOffsets;+ if (unlikely (!glyphAdvances.resize_exact (maxGlyphCount) ||+ !glyphOffsets.resize_exact (maxGlyphCount)))+ FAIL ("Failed to allocate glyph positioning data.");/* The -2 in the following is to compensate for possible* alignment needed after the WORD array. sizeof (WORD) == 2. */@@ -564,11 +576,11 @@ retry_getglyphs:float y_mult = font->y_multf;hr = analyzer->GetGlyphPlacements (textString,- clusterMap,- textProperties,+ clusterMap.arrayZ,+ textProperties.arrayZ,chars_len,- glyphIndices,- glyphProperties,+ glyphIndices.arrayZ,+ glyphProperties.arrayZ,glyphCount,fontFace,fontEmSize,@@ -579,8 +591,8 @@ retry_getglyphs:(const DWRITE_TYPOGRAPHIC_FEATURES**) range_features.arrayZ,range_char_counts.arrayZ,range_features.length,- glyphAdvances,- glyphOffsets);+ glyphAdvances.arrayZ,+ glyphOffsets.arrayZ);if (FAILED (hr))FAIL ("Analyzer failed to get glyph placements.");@@ -618,9 +630,9 @@ retry_getglyphs:info->cluster = vis_clusters[i];/* The rest is crap. Let's store position info there for now. */- info->mask = glyphAdvances[i];- info->var1.i32 = glyphOffsets[i].advanceOffset;- info->var2.i32 = glyphOffsets[i].ascenderOffset;+ info->mask = (hb_mask_t) hb_clamp_to<int32_t> (glyphAdvances[i]);+ info->var1.i32 = hb_clamp_to<int32_t> (glyphOffsets[i].advanceOffset);+ info->var2.i32 = hb_clamp_to<int32_t> (glyphOffsets[i].ascenderOffset);}/* Set glyph positions */@@ -631,9 +643,10 @@ retry_getglyphs:hb_glyph_position_t *pos = &buffer->pos[i];/* TODO vertical */- pos->x_advance = round (x_mult * (int32_t) info->mask);- pos->x_offset = round (x_mult * (isRightToLeft ? -info->var1.i32 : info->var1.i32));- pos->y_offset = round (y_mult * info->var2.i32);+ pos->x_advance = hb_clamp_to<hb_position_t> (round (x_mult * (int32_t) info->mask));+ double x_offset = isRightToLeft ? -(double) info->var1.i32 : info->var1.i32;+ pos->x_offset = hb_clamp_to<hb_position_t> (round ((double) x_mult * x_offset));+ pos->y_offset = hb_clamp_to<hb_position_t> (round (y_mult * info->var2.i32));}if (isRightToLeft) hb_buffer_reverse (buffer);@@ -641,13 +654,6 @@ retry_getglyphs:buffer->clear_glyph_flags ();buffer->unsafe_to_break ();- delete [] clusterMap;- delete [] glyphIndices;- delete [] textProperties;- delete [] glyphProperties;- delete [] glyphAdvances;- delete [] glyphOffsets;-/* Wow, done! */return true;}diff --git a/thirdparty/harfbuzz/src/hb-directwrite.cc b/thirdparty/harfbuzz/src/hb-directwrite.ccindex d941049713e..9d2e220572f 100644--- a/thirdparty/harfbuzz/src/hb-directwrite.cc+++ b/thirdparty/harfbuzz/src/hb-directwrite.cc@@ -47,13 +47,13 @@ static struct hb_directwrite_global_lazy_loader_t : hb_lazy_loader_t<hb_directwr{static hb_directwrite_global_t * create (){- hb_directwrite_global_t *global = new hb_directwrite_global_t;+ hb_directwrite_global_t *global = hb_directwrite_object_create<hb_directwrite_global_t> ();if (unlikely (!global))return nullptr;if (unlikely (!global->success)){- delete global;+ hb_directwrite_object_destroy (global);return nullptr;}@@ -63,7 +63,7 @@ static struct hb_directwrite_global_lazy_loader_t : hb_lazy_loader_t<hb_directwr}static void destroy (hb_directwrite_global_t *l){- delete l;+ hb_directwrite_object_destroy (l);}static hb_directwrite_global_t * get_null (){@@ -116,7 +116,9 @@ dw_face_create (hb_blob_t *blob, unsigned index)if (unlikely (!global))FAIL ("Couldn't load DirectWrite!");- DWriteFontFileStream *fontFileStream = new DWriteFontFileStream (blob);+ DWriteFontFileStream *fontFileStream = hb_directwrite_object_create<DWriteFontFileStream> (blob);+ if (unlikely (!fontFileStream))+ FAIL ("Failed to allocate font file stream!");IDWriteFontFile *fontFile;auto hr = global->dwriteFactory->CreateCustomFontFileReference (&fontFileStream->fontFileKey, sizeof (fontFileStream->fontFileKey),@@ -168,12 +170,11 @@ _hb_directwrite_get_file_blob (IDWriteFontFace *dw_face)if (FAILED (dw_face->GetFiles(&file_count, NULL)))return nullptr;- IDWriteFontFile **files = new IDWriteFontFile*[file_count];- if (FAILED (dw_face->GetFiles(&file_count, files)))- {- delete [] files;+ hb_vector_t<IDWriteFontFile *> files;+ if (unlikely (!files.resize_exact (file_count)))+ return nullptr;+ if (FAILED (dw_face->GetFiles(&file_count, files.arrayZ)))return nullptr;- }hb_blob_t *blob = nullptr;for (UINT32 i = 0; i < file_count; i++)@@ -209,7 +210,6 @@ _hb_directwrite_get_file_blob (IDWriteFontFace *dw_face)break;}- delete [] files;return blob;}@@ -315,7 +315,7 @@ hb_directwrite_face_create_from_file_or_fail (const char *file_name,* Creates an #hb_face_t face object from the specified* blob and face index.*- * This is similar in functionality to hb_face_create_from_blob_or_fail(),+ * This is similar in functionality to hb_face_create_or_fail(),* but uses the DirectWrite library for loading the font data.** Return value: (transfer full): The new face object, or `NULL` ifdiff --git a/thirdparty/harfbuzz/src/hb-directwrite.hh b/thirdparty/harfbuzz/src/hb-directwrite.hhindex 6c91b2bf5d3..8f686845e48 100644--- a/thirdparty/harfbuzz/src/hb-directwrite.hh+++ b/thirdparty/harfbuzz/src/hb-directwrite.hh@@ -47,7 +47,29 @@ typedef HRESULT (WINAPI *t_DWriteCreateFactory)(IUnknown **factory);-class DWriteFontFileLoader : public IDWriteFontFileLoader+template <typename Type, typename ...Ts>+static Type *+hb_directwrite_object_create (Ts&&... args)+{+ Type *obj = (Type *) hb_calloc (1, sizeof (Type));+ if (unlikely (!obj))+ return nullptr;++ return new (obj) Type (std::forward<Ts> (args)...);+}++template <typename Type>+static void+hb_directwrite_object_destroy (Type *obj)+{+ if (!obj)+ return;++ obj->~Type ();+ hb_free (obj);+}++class DWriteFontFileLoader final : public IDWriteFontFileLoader{private:hb_reference_count_t mRefCount;@@ -91,7 +113,7 @@ public:assert (refCount >= 0);if (refCount)return refCount;- delete this;+ hb_directwrite_object_destroy (this);return 0;}@@ -112,14 +134,14 @@ public:return S_OK;}- virtual ~DWriteFontFileLoader()+ ~DWriteFontFileLoader(){for (auto v : mFontStreams.values ())v->Release ();}};-class DWriteFontFileStream : public IDWriteFontFileStream+class DWriteFontFileStream final : public IDWriteFontFileStream{private:hb_reference_count_t mRefCount;@@ -145,7 +167,7 @@ public:assert (refCount >= 0);if (refCount)return refCount;- delete this;+ hb_directwrite_object_destroy (this);return 0;}@@ -181,7 +203,7 @@ public:virtual HRESULT STDMETHODCALLTYPEGetLastWriteTime (OUT UINT64* lastWriteTime) { return E_NOTIMPL; }- virtual ~DWriteFontFileStream();+ ~DWriteFontFileStream();};struct hb_directwrite_global_t@@ -194,8 +216,11 @@ struct hb_directwrite_global_tif (unlikely (hr != S_OK))return;- fontFileLoader = new DWriteFontFileLoader ();- dwriteFactory->RegisterFontFileLoader (fontFileLoader);+ fontFileLoader = hb_directwrite_object_create<DWriteFontFileLoader> ();+ if (unlikely (!fontFileLoader))+ return;+ if (unlikely (FAILED (dwriteFactory->RegisterFontFileLoader (fontFileLoader))))+ return;success = true;}@@ -208,8 +233,8 @@ struct hb_directwrite_global_t}bool success = false;- IDWriteFactory *dwriteFactory;- DWriteFontFileLoader *fontFileLoader;+ IDWriteFactory *dwriteFactory = nullptr;+ DWriteFontFileLoader *fontFileLoader = nullptr;};diff --git a/thirdparty/harfbuzz/src/hb-draw.cc b/thirdparty/harfbuzz/src/hb-draw.ccindex 0997153f85f..11f4e9a1f35 100644--- a/thirdparty/harfbuzz/src/hb-draw.cc+++ b/thirdparty/harfbuzz/src/hb-draw.cc@@ -65,12 +65,20 @@ hb_draw_quadratic_to_nil (hb_draw_funcs_t *dfuncs, void *draw_data,float to_x, float to_y,void *user_data HB_UNUSED){-#define HB_TWO_THIRD 0.66666666666666666666666667f+ /* Compute in double precision, so that the result does not depend+ * on how the compiler evaluates float expressions. */+#define HB_TWO_THIRD 0.66666666666666666666666667+ double current_x = (double) st->current_x;+ double current_y = (double) st->current_y;+ double cx = (double) control_x;+ double cy = (double) control_y;+ double tx = (double) to_x;+ double ty = (double) to_y;dfuncs->emit_cubic_to (draw_data, *st,- st->current_x + (control_x - st->current_x) * HB_TWO_THIRD,- st->current_y + (control_y - st->current_y) * HB_TWO_THIRD,- to_x + (control_x - to_x) * HB_TWO_THIRD,- to_y + (control_y - to_y) * HB_TWO_THIRD,+ (float) (current_x + (cx - current_x) * HB_TWO_THIRD),+ (float) (current_y + (cy - current_y) * HB_TWO_THIRD),+ (float) (tx + (cx - tx) * HB_TWO_THIRD),+ (float) (ty + (cy - ty) * HB_TWO_THIRD),to_x, to_y);#undef HB_TWO_THIRD}diff --git a/thirdparty/harfbuzz/src/hb-face-builder.cc b/thirdparty/harfbuzz/src/hb-face-builder.ccindex d62bd9605f4..cb55e4b8fd3 100644--- a/thirdparty/harfbuzz/src/hb-face-builder.cc+++ b/thirdparty/harfbuzz/src/hb-face-builder.cc@@ -181,15 +181,18 @@ _hb_face_builder_get_table_tags (const hb_face_t *face HB_UNUSED,// Not much to do...}sorted_tags.qsort ([] (const hb_tag_t &a, const hb_tag_t &b) {- return a < b;+ return (a > b) - (a < b);});auto array = sorted_tags.as_array ().sub_array (start_offset, table_count);- auto out = hb_array (table_tags, *table_count);+ if (table_tags)+ {+ auto out = hb_array (table_tags, *table_count);- + array.iter ()- | hb_sink (out)- ;+ + array.iter ()+ | hb_sink (out)+ ;+ }return population;}diff --git a/thirdparty/harfbuzz/src/hb-face.cc b/thirdparty/harfbuzz/src/hb-face.ccindex b0cc787d0d1..ee633a62451 100644--- a/thirdparty/harfbuzz/src/hb-face.cc+++ b/thirdparty/harfbuzz/src/hb-face.cc@@ -909,7 +909,7 @@ hb_face_set_get_table_tags_func (hb_face_t *face,* @start_offset: The index of first table tag to retrieve* @table_count: (inout): Input = the maximum number of table tags to return;* Output = the actual number of table tags returned (may be zero)- * @table_tags: (out) (array length=table_count): The array of table tags found+ * @table_tags: (out) (array length=table_count) (nullable): The array of table tags found** Fetches a list of all table tags for a face, if possible. The list returned will* begin at the offset provideddiff --git a/thirdparty/harfbuzz/src/hb-face.h b/thirdparty/harfbuzz/src/hb-face.hindex b8386f0afb1..4e0902cfd56 100644--- a/thirdparty/harfbuzz/src/hb-face.h+++ b/thirdparty/harfbuzz/src/hb-face.h@@ -169,7 +169,7 @@ hb_face_get_glyph_count (const hb_face_t *face);* @start_offset: The index of first table tag to retrieve* @table_count: (inout): Input = the maximum number of table tags to return;* Output = the actual number of table tags returned (may be zero)- * @table_tags: (out) (array length=table_count): The array of table tags found+ * @table_tags: (out) (array length=table_count) (nullable): The array of table tags found* @user_data: User data pointer passed by the caller** Callback function for hb_face_get_table_tags().diff --git a/thirdparty/harfbuzz/src/hb-font.cc b/thirdparty/harfbuzz/src/hb-font.ccindex 96fcff50144..ecb14836190 100644--- a/thirdparty/harfbuzz/src/hb-font.cc+++ b/thirdparty/harfbuzz/src/hb-font.cc@@ -1670,9 +1670,7 @@ hb_font_t::paint_glyph (hb_codepoint_t glyph,return;/* Fallback for outline glyph. */- paint_funcs->push_clip_glyph (paint_data, glyph, this);- paint_funcs->color (paint_data, true, foreground);- paint_funcs->pop_clip (paint_data);+ paint_funcs->fill_glyph (paint_data, glyph, this, true, foreground);}@@ -2500,9 +2498,9 @@ hb_font_get_face (hb_font_t *font)/*** hb_font_set_funcs:* @font: #hb_font_t to work upon- * @klass: (closure font_data) (destroy destroy) (scope notified): The font-functions structure.+ * @klass: The font-functions structure.* @font_data: Data to attach to @font- * @destroy: (nullable): The function to call when @font_data is not needed anymore+ * @destroy: (nullable) (scope async) (closure font_data): The function to call when @font_data is not needed anymore** Replaces the font-functions structure attached to a font, updating* the font's user-data with @font-data and the @destroy callback.@@ -2540,8 +2538,8 @@ hb_font_set_funcs (hb_font_t *font,/*** hb_font_set_funcs_data:* @font: #hb_font_t to work upon- * @font_data: (destroy destroy) (scope notified): Data to attach to @font- * @destroy: (nullable): The function to call when @font_data is not needed anymore+ * @font_data: Data to attach to @font+ * @destroy: (nullable) (scope async) (closure font_data): The function to call when @font_data is not needed anymore** Replaces the user data attached to a font, updating the font's* @destroy callback.diff --git a/thirdparty/harfbuzz/src/hb-font.hh b/thirdparty/harfbuzz/src/hb-font.hhindex 842d0ea2d75..e6a9b2ed990 100644--- a/thirdparty/harfbuzz/src/hb-font.hh+++ b/thirdparty/harfbuzz/src/hb-font.hh@@ -158,12 +158,12 @@ struct hb_font_t/* Convert from font-space to user-space */int64_t dir_mult (hb_direction_t direction){ return HB_DIRECTION_IS_VERTICAL(direction) ? y_mult : x_mult; }- hb_position_t em_scale_x (int16_t v) { return em_mult (v, x_mult); }- hb_position_t em_scale_y (int16_t v) { return em_mult (v, y_mult); }+ hb_position_t em_scale_x (int32_t v) { return em_mult (v, x_mult); }+ hb_position_t em_scale_y (int32_t v) { return em_mult (v, y_mult); }hb_position_t em_scalef_x (float v) { return em_multf (v, x_multf); }hb_position_t em_scalef_y (float v) { return em_multf (v, y_multf); }- float em_fscale_x (int16_t v) { return em_fmult (v, x_multf); }- float em_fscale_y (int16_t v) { return em_fmult (v, y_multf); }+ float em_fscale_x (int32_t v) { return em_fmult (v, x_multf); }+ float em_fscale_y (int32_t v) { return em_fmult (v, y_multf); }float em_fscalef_x (float v) { return em_fmultf (v, x_multf); }float em_fscalef_y (float v) { return em_fmultf (v, y_multf); }hb_position_t em_scale_dir (int16_t v, hb_direction_t direction)@@ -200,15 +200,15 @@ struct hb_font_tvoid scale_glyph_extents (hb_glyph_extents_t *extents){- float x1 = em_scale_x (extents->x_bearing);- float y1 = em_scale_y (extents->y_bearing);- float x2 = em_scale_x (extents->x_bearing + extents->width);- float y2 = em_scale_y (extents->y_bearing + extents->height);-- extents->x_bearing = roundf (x1);- extents->y_bearing = roundf (y1);- extents->width = roundf (x2) - extents->x_bearing;- extents->height = roundf (y2) - extents->y_bearing;+ float x1 = em_fscale_x (extents->x_bearing);+ float y1 = em_fscale_y (extents->y_bearing);+ float x2 = em_fscale_x (extents->x_bearing + extents->width);+ float y2 = em_fscale_y (extents->y_bearing + extents->height);++ extents->x_bearing = floorf (x1);+ extents->y_bearing = floorf (y1);+ extents->width = ceilf (x2) - extents->x_bearing;+ extents->height = ceilf (y2) - extents->y_bearing;}void synthetic_glyph_extents (hb_glyph_extents_t *extents)@@ -1144,10 +1144,8 @@ struct hb_font_tx_multf = x_scale / upem;y_multf = y_scale / upem;- bool x_neg = x_scale < 0;- x_mult = (x_neg ? -((int64_t) -x_scale << 16) : ((int64_t) x_scale << 16)) / upem;- bool y_neg = y_scale < 0;- y_mult = (y_neg ? -((int64_t) -y_scale << 16) : ((int64_t) y_scale << 16)) / upem;+ x_mult = (int64_t) x_scale * 0x10000 / upem;+ y_mult = (int64_t) y_scale * 0x10000 / upem;is_synthetic = x_embolden || y_embolden || slant;@@ -1161,13 +1159,13 @@ struct hb_font_tserial++;}- hb_position_t em_mult (int16_t v, int64_t mult)+ hb_position_t em_mult (int32_t v, int64_t mult){ return (hb_position_t) ((v * mult + 32768) >> 16); }hb_position_t em_multf (float v, float mult){ return (hb_position_t) roundf (em_fmultf (v, mult)); }float em_fmultf (float v, float mult){ return v * mult; }- float em_fmult (int16_t v, float mult)+ float em_fmult (int32_t v, float mult){ return (float) v * mult; }};DECLARE_NULL_INSTANCE (hb_font_t);diff --git a/thirdparty/harfbuzz/src/hb-ft-colr.hh b/thirdparty/harfbuzz/src/hb-ft-colr.hhindex d7a3611696c..933d5894ebb 100644--- a/thirdparty/harfbuzz/src/hb-ft-colr.hh+++ b/thirdparty/harfbuzz/src/hb-ft-colr.hh@@ -78,6 +78,31 @@ static void_hb_ft_paint (hb_ft_paint_context_t *c,FT_OpaquePaint opaque_paint);+static void+_hb_ft_unscale_clip_box (hb_font_t *font,+ const FT_ClipBox *clip_box,+ float *xmin, float *ymin,+ float *xmax, float *ymax)+{+ /* The FreeType ClipBox is in scaled coordinates. Convert it back to+ * font units before pushing it under the font transform.+ */+ float upem = font->face->get_upem ();+ float xscale = upem / (font->x_scale ? font->x_scale : upem);+ float yscale = upem / (font->y_scale ? font->y_scale : upem);++ *xmin = clip_box->bottom_left.x * xscale;+ *ymin = clip_box->bottom_left.y * yscale;+ *xmax = clip_box->top_right.x * xscale;+ *ymax = clip_box->top_right.y * yscale;+}++static unsigned+_hb_ft_color_alpha (unsigned alpha, unsigned alpha_mult)+{+ return (alpha * alpha_mult + (1 << 13)) >> 14;+}+struct hb_ft_paint_context_t{hb_ft_paint_context_t (const hb_ft_font_t *ft_font_,@@ -138,7 +163,7 @@ _hb_ft_color_line_get_color_stops (hb_color_line_t *color_line,FT_ColorLine *cl = (FT_ColorLine *) color_line_data;hb_ft_paint_context_t *c = (hb_ft_paint_context_t *) user_data;- if (count)+ if (count && color_stops){FT_ColorStop stop;unsigned wrote = 0;@@ -151,11 +176,22 @@ _hb_ft_color_line_get_color_stops (hb_color_line_t *color_line,}while (cl->color_stop_iterator.current_color_stop < start)- FT_Get_Colorline_Stops(c->ft_font->ft_face,+ {+ if (!FT_Get_Colorline_Stops(c->ft_font->ft_face,&stop,- &cl->color_stop_iterator);+ &cl->color_stop_iterator))+ {+ // FT_Get_Colorline_Stops can in some cases return 0, and+ // does not advance the iterator. So stop iteration to prevent+ // infinite loop here.+ //+ // reset the iterator for next time+ cl->color_stop_iterator = iter;+ return cl->color_stop_iterator.num_color_stops;+ }+ }- while (count && *count &&+ while (wrote < *count &&FT_Get_Colorline_Stops(c->ft_font->ft_face,&stop,&cl->color_stop_iterator))@@ -171,7 +207,8 @@ _hb_ft_color_line_get_color_stops (hb_color_line_t *color_line,color_stops->color = HB_COLOR (hb_color_get_blue (c->foreground),hb_color_get_green (c->foreground),hb_color_get_red (c->foreground),- (hb_color_get_alpha (c->foreground) * stop.color.alpha) >> 14);+ _hb_ft_color_alpha (hb_color_get_alpha (c->foreground),+ stop.color.alpha));else{hb_color_t color;@@ -180,7 +217,8 @@ _hb_ft_color_line_get_color_stops (hb_color_line_t *color_line,color_stops->color = HB_COLOR (hb_color_get_blue (color),hb_color_get_green (color),hb_color_get_red (color),- (hb_color_get_alpha (color) * stop.color.alpha) >> 14);+ _hb_ft_color_alpha (hb_color_get_alpha (color),+ stop.color.alpha));}else if (c->palette){@@ -188,7 +226,8 @@ _hb_ft_color_line_get_color_stops (hb_color_line_t *color_line,color_stops->color = HB_COLOR (ft_color.blue,ft_color.green,ft_color.red,- (ft_color.alpha * stop.color.alpha) >> 14);+ _hb_ft_color_alpha (ft_color.alpha,+ stop.color.alpha));}elsecolor_stops->color = HB_COLOR (0, 0, 0, 0);@@ -199,7 +238,6 @@ _hb_ft_color_line_get_color_stops (hb_color_line_t *color_line,}*count = wrote;-// reset the iterator for next timecl->color_stop_iterator = iter;}@@ -222,6 +260,42 @@ _hb_ft_color_line_get_extend (hb_color_line_t *color_line,}}+static void+_hb_ft_get_solid_color (hb_ft_paint_context_t *c,+ const FT_ColorIndex &color_index,+ hb_bool_t *is_foreground,+ hb_color_t *color)+{+ *is_foreground = color_index.palette_index == 0xFFFF;++ if (*is_foreground)+ {+ *color = HB_COLOR (hb_color_get_blue (c->foreground),+ hb_color_get_green (c->foreground),+ hb_color_get_red (c->foreground),+ _hb_ft_color_alpha (hb_color_get_alpha (c->foreground),+ color_index.alpha));+ return;+ }++ if (c->funcs->custom_palette_color (c->data, color_index.palette_index, color))+ {+ *color = HB_COLOR (hb_color_get_blue (*color),+ hb_color_get_green (*color),+ hb_color_get_red (*color),+ _hb_ft_color_alpha (hb_color_get_alpha (*color),+ color_index.alpha));+ return;+ }++ FT_Color ft_color = c->palette[color_index.palette_index];+ *color = HB_COLOR (ft_color.blue,+ ft_color.green,+ ft_color.red,+ _hb_ft_color_alpha (ft_color.alpha,+ color_index.alpha));+}+void_hb_ft_paint (hb_ft_paint_context_t *c,FT_OpaquePaint opaque_paint)@@ -252,31 +326,9 @@ _hb_ft_paint (hb_ft_paint_context_t *c,break;case FT_COLR_PAINTFORMAT_SOLID:{- bool is_foreground = paint.u.solid.color.palette_index == 0xFFFF;+ hb_bool_t is_foreground;hb_color_t color;- if (is_foreground)- color = HB_COLOR (hb_color_get_blue (c->foreground),- hb_color_get_green (c->foreground),- hb_color_get_red (c->foreground),- (hb_color_get_alpha (c->foreground) * paint.u.solid.color.alpha) >> 14);- else- {- if (c->funcs->custom_palette_color (c->data, paint.u.solid.color.palette_index, &color))- {- color = HB_COLOR (hb_color_get_blue (color),- hb_color_get_green (color),- hb_color_get_red (color),- (hb_color_get_alpha (color) * paint.u.solid.color.alpha) >> 14);- }- else- {- FT_Color ft_color = c->palette[paint.u.solid.color.palette_index];- color = HB_COLOR (ft_color.blue,- ft_color.green,- ft_color.red,- (ft_color.alpha * paint.u.solid.color.alpha) >> 14);- }- }+ _hb_ft_get_solid_color (c, paint.u.solid.color, &is_foreground, &color);c->funcs->color (c->data, is_foreground, color);}break;@@ -331,6 +383,26 @@ _hb_ft_paint (hb_ft_paint_context_t *c,break;case FT_COLR_PAINTFORMAT_GLYPH:{+ /* Optimize cases that can use a simple fill-glyph operation. */+ FT_COLR_Paint fill;+ if (likely (c->depth_left > 0 && c->edge_count > 0) &&+ FT_Get_Paint (ft_face, paint.u.glyph.paint, &fill) &&+ fill.format == FT_COLR_PAINTFORMAT_SOLID)+ {+ hb_bool_t is_foreground;+ hb_color_t color;+ _hb_ft_get_solid_color (c, fill.u.solid.color, &is_foreground, &color);++ c->edge_count--;+ c->funcs->push_inverse_font_transform (c->data, c->font);+ c->ft_font->lock.unlock ();+ c->funcs->fill_glyph (c->data, paint.u.glyph.glyphID, c->font,+ is_foreground, color);+ c->ft_font->lock.lock ();+ c->funcs->pop_transform (c->data);+ break;+ }+c->funcs->push_inverse_font_transform (c->data, c->font);c->ft_font->lock.unlock ();c->funcs->push_clip_glyph (c->data, paint.u.glyph.glyphID, c->font);@@ -372,19 +444,10 @@ _hb_ft_paint (hb_ft_paint_context_t *c,if (has_clip_box){- /* The FreeType ClipBox is in scaled coordinates, whereas we need- * unscaled clipbox here. Oh well...- */-- float upem = c->font->face->get_upem ();- float xscale = upem / (c->font->x_scale ? c->font->x_scale : upem);- float yscale = upem / (c->font->y_scale ? c->font->y_scale : upem);-- c->funcs->push_clip_rectangle (c->data,- clip_box.bottom_left.x * xscale,- clip_box.bottom_left.y * yscale,- clip_box.top_right.x * xscale,- clip_box.top_right.y * yscale);+ float xmin, ymin, xmax, ymax;+ _hb_ft_unscale_clip_box (c->font, &clip_box,+ &xmin, &ymin, &xmax, &ymax);+ c->funcs->push_clip_rectangle (c->data, xmin, ymin, xmax, ymax);}c->recurse (other_paint);@@ -515,19 +578,9 @@ hb_ft_paint_glyph_colr (hb_font_t *font,hb_decycler_node_t node (c.glyphs_decycler);node.visit (gid);- bool clip = false;- bool is_bounded = false;FT_ClipBox clip_box;- if (FT_Get_Color_Glyph_ClipBox (ft_face, gid, &clip_box))- {- c.funcs->push_clip_rectangle (c.data,- clip_box.bottom_left.x,- clip_box.bottom_left.y,- clip_box.top_right.x,- clip_box.top_right.y);- clip = true;- is_bounded = true;- }+ bool clip = FT_Get_Color_Glyph_ClipBox (ft_face, gid, &clip_box);+ bool is_bounded = clip;if (!is_bounded){auto *bounded_funcs = hb_paint_bounded_get_funcs ();@@ -543,14 +596,22 @@ hb_ft_paint_glyph_colr (hb_font_t *font,c.funcs->push_font_transform (c.data, font);+ if (clip)+ {+ float xmin, ymin, xmax, ymax;+ _hb_ft_unscale_clip_box (font, &clip_box,+ &xmin, &ymin, &xmax, &ymax);+ c.funcs->push_clip_rectangle (c.data, xmin, ymin, xmax, ymax);+ }+if (is_bounded)c.recurse (paint);- c.funcs->pop_transform (c.data);-if (clip)c.funcs->pop_clip (c.data);+ c.funcs->pop_transform (c.data);+return true;}@@ -580,10 +641,8 @@ hb_ft_paint_glyph_colr (hb_font_t *font,}ft_font->lock.unlock ();- paint_funcs->push_clip_glyph (paint_data, layer_glyph_index, font);+ paint_funcs->fill_glyph (paint_data, layer_glyph_index, font, is_foreground, color);ft_font->lock.lock ();- paint_funcs->color (paint_data, is_foreground, color);- paint_funcs->pop_clip (paint_data);} while (FT_Get_Color_Glyph_Layer(ft_face,gid,diff --git a/thirdparty/harfbuzz/src/hb-ft.cc b/thirdparty/harfbuzz/src/hb-ft.ccindex 8ac5db77462..ce66f1145d8 100644--- a/thirdparty/harfbuzz/src/hb-ft.cc+++ b/thirdparty/harfbuzz/src/hb-ft.cc@@ -508,23 +508,24 @@ hb_ft_get_glyph_h_advances (hb_font_t* font, void* font_data,for (unsigned int i = 0; i < count; i++){- FT_Fixed v = 0;+ hb_position_t advance;hb_codepoint_t glyph = *first_glyph;unsigned int cv;if (ft_font->advance_cache.get (glyph, &cv))- v = cv;+ advance = (hb_position_t) cv;else{+ FT_Fixed v = 0;FT_Get_Advance (ft_face, glyph, load_flags, &v);/* Work around bug that FreeType seems to return negative advance* for variable-set fonts if x_scale is negative! */- v = abs (v);- v = (int) (v * x_mult + (1<<9)) >> 10;- ft_font->advance_cache.set (glyph, v);+ double scaled = trunc (fabs ((double) v) * (double) x_mult + (1<<9)) / (1<<10);+ advance = hb_clamp_to<hb_position_t> (floor (scaled));+ ft_font->advance_cache.set (glyph, advance);}- *first_advance = v;+ *first_advance = advance;first_glyph = &StructAtOffsetUnaligned<hb_codepoint_t> (first_glyph, glyph_stride);first_advance = &StructAtOffsetUnaligned<hb_position_t> (first_advance, advance_stride);}@@ -562,9 +563,9 @@ hb_ft_get_glyph_v_advance (hb_font_t *font,/* Note: FreeType's vertical metrics grows downward while other FreeType coordinates* have a Y growing upward. Hence the extra negation. */- v = ((-v + (1<<9)) >> 10);+ double advance = floor ((-(double) v + (1<<9)) / (1<<10));- return (hb_position_t) (y_mult * v);+ return hb_clamp_to<hb_position_t> ((double) y_mult * advance);}#endif@@ -605,11 +606,12 @@ hb_ft_get_glyph_v_origin (hb_font_t *font,/* Note: FreeType's vertical metrics grows downward while other FreeType coordinates* have a Y growing upward. Hence the extra negation. */- *x = ft_face->glyph->metrics.horiBearingX - ft_face->glyph->metrics.vertBearingX;- *y = ft_face->glyph->metrics.horiBearingY - (-ft_face->glyph->metrics.vertBearingY);-- *x = (hb_position_t) (x_mult * *x);- *y = (hb_position_t) (y_mult * *y);+ *x = hb_clamp_to<hb_position_t> ((double) x_mult *+ ((double) ft_face->glyph->metrics.horiBearingX -+ ft_face->glyph->metrics.vertBearingX));+ *y = hb_clamp_to<hb_position_t> ((double) y_mult *+ ((double) ft_face->glyph->metrics.horiBearingY ++ ft_face->glyph->metrics.vertBearingY));return true;}@@ -633,7 +635,7 @@ hb_ft_get_glyph_h_kerning (hb_font_t *font,if (FT_Get_Kerning (ft_font->ft_face, left_glyph, right_glyph, mode, &kerningv))return 0;- return kerningv.x;+ return hb_clamp_to<hb_position_t> ((int64_t) kerningv.x);}#endif@@ -717,10 +719,15 @@ hb_ft_get_glyph_extents (hb_font_t *font,float x2 = x1 + x_mult * ft_face->glyph->metrics.width;float y2 = y1 + y_mult * -ft_face->glyph->metrics.height;- extents->x_bearing = roundf (x1);- extents->y_bearing = roundf (y1);- extents->width = roundf (x2) - extents->x_bearing;- extents->height = roundf (y2) - extents->y_bearing;+ double rx1 = (double) roundf (x1);+ double ry1 = (double) roundf (y1);+ double rx2 = (double) roundf (x2);+ double ry2 = (double) roundf (y2);++ extents->x_bearing = hb_clamp_to<hb_position_t> (rx1);+ extents->y_bearing = hb_clamp_to<hb_position_t> (ry1);+ extents->width = hb_clamp_to<hb_position_t> (rx2 - rx1);+ extents->height = hb_clamp_to<hb_position_t> (ry2 - ry1);return true;}@@ -841,22 +848,24 @@ hb_ft_get_font_h_extents (hb_font_t *font HB_UNUSED,if (ft_face->units_per_EM != 0){- metrics->ascender = FT_MulFix(ft_face->ascender, ft_face->size->metrics.y_scale);- metrics->descender = FT_MulFix(ft_face->descender, ft_face->size->metrics.y_scale);- metrics->line_gap = FT_MulFix( ft_face->height, ft_face->size->metrics.y_scale ) - (metrics->ascender - metrics->descender);+ double ascender = FT_MulFix(ft_face->ascender, ft_face->size->metrics.y_scale);+ double descender = FT_MulFix(ft_face->descender, ft_face->size->metrics.y_scale);+ double height = FT_MulFix( ft_face->height, ft_face->size->metrics.y_scale );+ metrics->ascender = hb_clamp_to<hb_position_t> ((double) y_mult * ascender);+ metrics->descender = hb_clamp_to<hb_position_t> ((double) y_mult * descender);+ metrics->line_gap = hb_clamp_to<hb_position_t> ((double) y_mult * (height - (ascender - descender)));}else{/* Bitmap-only font, eg. color bitmap font. */- metrics->ascender = ft_face->size->metrics.ascender;- metrics->descender = ft_face->size->metrics.descender;- metrics->line_gap = ft_face->size->metrics.height - (metrics->ascender - metrics->descender);+ double ascender = ft_face->size->metrics.ascender;+ double descender = ft_face->size->metrics.descender;+ double height = ft_face->size->metrics.height;+ metrics->ascender = hb_clamp_to<hb_position_t> ((double) y_mult * ascender);+ metrics->descender = hb_clamp_to<hb_position_t> ((double) y_mult * descender);+ metrics->line_gap = hb_clamp_to<hb_position_t> ((double) y_mult * (height - (ascender - descender)));}- metrics->ascender = (hb_position_t) (y_mult * metrics->ascender);- metrics->descender = (hb_position_t) (y_mult * metrics->descender);- metrics->line_gap = (hb_position_t) (y_mult * metrics->line_gap);-return true;}@@ -1152,23 +1161,29 @@ _hb_ft_get_table_tags (const hb_face_t *face HB_UNUSED,if (!table_count)return population;- else- *table_count = 0;if (unlikely (start_offset >= population))+ {+ *table_count = 0;return population;+ }- unsigned end_offset = hb_min (start_offset + *table_count, (unsigned) population);- if (unlikely (end_offset < start_offset))+ unsigned end_offset = start_offset + *table_count;+ if (unlikely (end_offset < start_offset)) /* Overflow. */+ {+ *table_count = 0;return population;+ }+ end_offset = hb_min (end_offset, (unsigned) population);*table_count = end_offset - start_offset;- for (unsigned i = start_offset; i < end_offset; i++)- {- FT_ULong tag = 0, length;- FT_Sfnt_Table_Info (ft_face, i, &tag, &length);- table_tags[i - start_offset] = tag;- }+ if (table_tags)+ for (unsigned i = start_offset; i < end_offset; i++)+ {+ FT_ULong tag = 0, length;+ FT_Sfnt_Table_Info (ft_face, i, &tag, &length);+ table_tags[i - start_offset] = tag;+ }return population;}@@ -1176,8 +1191,8 @@ _hb_ft_get_table_tags (const hb_face_t *face HB_UNUSED,/*** hb_ft_face_create:- * @ft_face: (destroy destroy) (scope notified): FT_Face to work upon- * @destroy: (nullable): A callback to call when the face object is not needed anymore+ * @ft_face: FT_Face to work upon+ * @destroy: (nullable) (scope async): A callback to call when the face object is not needed anymore** Creates an #hb_face_t face object from the specified FT_Face.*@@ -1300,8 +1315,8 @@ hb_ft_face_create_cached (FT_Face ft_face)/*** hb_ft_font_create:- * @ft_face: (destroy destroy) (scope notified): FT_Face to work upon- * @destroy: (nullable): A callback to call when the font object is not needed anymore+ * @ft_face: FT_Face to work upon+ * @destroy: (nullable) (scope async): A callback to call when the font object is not needed anymore** Creates an #hb_font_t font object from the specified FT_Face.*@@ -1609,7 +1624,7 @@ _destroy_blob (void *p)* Creates an #hb_face_t face object from the specified* font blob and face index.*- * This is similar in functionality to hb_face_create_from_blob_or_fail(),+ * This is similar in functionality to hb_face_create_or_fail(),* but uses the FreeType library for loading the font blob. This can* be useful, for example, to load WOFF and WOFF2 font data.*diff --git a/thirdparty/harfbuzz/src/hb-graphite2.cc b/thirdparty/harfbuzz/src/hb-graphite2.ccindex ed157258562..6d835271827 100644--- a/thirdparty/harfbuzz/src/hb-graphite2.cc+++ b/thirdparty/harfbuzz/src/hb-graphite2.cc@@ -219,7 +219,12 @@ struct hb_graphite2_cluster_t {unsigned int base_glyph;unsigned int num_glyphs;unsigned int cluster;- int advance;+ hb_position_t advance;+};++struct hb_graphite2_glyph_t {+ hb_codepoint_t codepoint;+ unsigned int cluster;};hb_bool_t@@ -262,7 +267,7 @@ _hb_graphite2_shape (hb_shape_plan_t *shape_plan HB_UNUSED,gr_segment *seg = nullptr;const gr_slot *is;unsigned int ci = 0, ic = 0;- int curradvx = 0, curradvy = 0;+ hb_position_t curradvx = 0, curradvy = 0;unsigned int scratch_size;hb_buffer_t::scratch_buffer_t *scratch = buffer->get_scratch_buffer (&scratch_size);@@ -294,7 +299,7 @@ _hb_graphite2_shape (hb_shape_plan_t *shape_plan HB_UNUSED,(void) buffer->ensure (glyph_count);scratch = buffer->get_scratch_buffer (&scratch_size);while ((DIV_CEIL (sizeof (hb_graphite2_cluster_t) * buffer->len, sizeof (*scratch)) +- DIV_CEIL (sizeof (hb_codepoint_t) * glyph_count, sizeof (*scratch))) > scratch_size)+ DIV_CEIL (sizeof (hb_graphite2_glyph_t) * glyph_count, sizeof (*scratch))) > scratch_size){if (unlikely (!buffer->ensure (buffer->allocated * 2))){@@ -315,37 +320,49 @@ _hb_graphite2_shape (hb_shape_plan_t *shape_plan HB_UNUSED,} while (0)ALLOCATE_ARRAY (hb_graphite2_cluster_t, clusters, buffer->len);- ALLOCATE_ARRAY (hb_codepoint_t, gids, glyph_count);+ ALLOCATE_ARRAY (hb_graphite2_glyph_t, glyphs, glyph_count);#undef ALLOCATE_ARRAYhb_memset (clusters, 0, sizeof (clusters[0]) * buffer->len);- hb_codepoint_t *pg = gids;+ hb_graphite2_glyph_t *pg = glyphs;clusters[0].cluster = buffer->info[0].cluster;unsigned int upem = hb_face_get_upem (face);float xscale = (float) font->x_scale / upem;float yscale = (float) font->y_scale / upem;yscale *= yscale / xscale;- unsigned int curradv = 0;+ hb_position_t curradv = 0;if (HB_DIRECTION_IS_BACKWARD (direction)){- curradv = gr_slot_origin_X(gr_seg_first_slot(seg)) * xscale;- clusters[0].advance = gr_seg_advance_X(seg) * xscale - curradv;+ curradv = hb_clamp_to<hb_position_t> (gr_slot_origin_X(gr_seg_first_slot(seg)) * xscale);+ clusters[0].advance = hb_clamp_to<hb_position_t> ((double) (gr_seg_advance_X(seg) * xscale) - curradv);}elseclusters[0].advance = 0;for (is = gr_seg_first_slot (seg), ic = 0; is; is = gr_slot_next_in_segment (is), ic++){- unsigned int before = gr_slot_before (is);- unsigned int after = gr_slot_after (is);- *pg = gr_slot_gid (is);+ int slot_before = gr_slot_before (is);+ int slot_after = gr_slot_after (is);+ if (unlikely (slot_before < 0 ||+ slot_after < slot_before ||+ (unsigned int) slot_after >= buffer->len))+ {+ if (feats) gr_featureval_destroy (feats);+ gr_seg_destroy (seg);+ return false;+ }+ unsigned int before = (unsigned int) slot_before;+ unsigned int after = (unsigned int) slot_after;+ pg->codepoint = gr_slot_gid (is);+ pg->cluster = hb_min (buffer->info[before].cluster,+ buffer->info[after].cluster);pg++;while (clusters[ci].base_char > before && ci){clusters[ci-1].num_chars += clusters[ci].num_chars;clusters[ci-1].num_glyphs += clusters[ci].num_glyphs;- clusters[ci-1].advance += clusters[ci].advance;+ clusters[ci-1].advance = hb_saturate_add (clusters[ci-1].advance, clusters[ci].advance);ci--;}@@ -359,14 +376,16 @@ _hb_graphite2_shape (hb_shape_plan_t *shape_plan HB_UNUSED,c->num_glyphs = 0;if (HB_DIRECTION_IS_BACKWARD (direction)){- c->advance = curradv - gr_slot_origin_X(is) * xscale;- curradv -= c->advance;+ c->advance = hb_clamp_to<hb_position_t> ((double) curradv -+ (double) (gr_slot_origin_X(is) * xscale));+ curradv = hb_saturate_sub (curradv, c->advance);}else{- auto origin_X = gr_slot_origin_X (is) * xscale;+ hb_position_t origin_X = hb_clamp_to<hb_position_t> (gr_slot_origin_X (is) * xscale);c->advance = 0;- clusters[ci].advance += origin_X - curradv;+ clusters[ci].advance = hb_saturate_add (clusters[ci].advance,+ hb_saturate_sub (origin_X, curradv));curradv = origin_X;}ci++;@@ -378,9 +397,10 @@ _hb_graphite2_shape (hb_shape_plan_t *shape_plan HB_UNUSED,}if (HB_DIRECTION_IS_BACKWARD (direction))- clusters[ci].advance += curradv;+ clusters[ci].advance = hb_saturate_add (clusters[ci].advance, curradv);else- clusters[ci].advance += gr_seg_advance_X(seg) * xscale - curradv;+ clusters[ci].advance = hb_clamp_to<hb_position_t> ((double) clusters[ci].advance ++ (double) (gr_seg_advance_X(seg) * xscale) - curradv);ci++;for (unsigned int i = 0; i < ci; ++i)@@ -388,15 +408,22 @@ _hb_graphite2_shape (hb_shape_plan_t *shape_plan HB_UNUSED,for (unsigned int j = 0; j < clusters[i].num_glyphs; ++j){hb_glyph_info_t *info = &buffer->info[clusters[i].base_glyph + j];- info->codepoint = gids[clusters[i].base_glyph + j];- info->cluster = clusters[i].cluster;+ info->codepoint = glyphs[clusters[i].base_glyph + j].codepoint;+ info->cluster = HB_BUFFER_CLUSTER_LEVEL_IS_MONOTONE (buffer->cluster_level) ?+ glyphs[clusters[i].base_glyph + j].cluster :+ clusters[i].cluster;info->var1.i32 = clusters[i].advance; // all glyphs in the cluster get the same advance+ info->var2.u32 = i; // Graphite cluster index}}buffer->len = glyph_count;+ for (unsigned int i = 0; i < ci; ++i)+ buffer->merge_clusters (clusters[i].base_glyph,+ clusters[i].base_glyph + clusters[i].num_glyphs);+/* Positioning. */- unsigned int currclus = UINT_MAX;+ unsigned int curr_gr_cluster = UINT_MAX;const hb_glyph_info_t *info = buffer->info;hb_glyph_position_t *pPos = hb_buffer_get_glyph_positions (buffer, nullptr);if (!HB_DIRECTION_IS_BACKWARD (direction))@@ -404,36 +431,37 @@ _hb_graphite2_shape (hb_shape_plan_t *shape_plan HB_UNUSED,curradvx = 0;for (is = gr_seg_first_slot (seg); is; pPos++, ++info, is = gr_slot_next_in_segment (is)){- pPos->x_offset = gr_slot_origin_X (is) * xscale - curradvx;- pPos->y_offset = gr_slot_origin_Y (is) * yscale - curradvy;- if (info->cluster != currclus) {+ pPos->x_offset = hb_clamp_to<hb_position_t> ((double) (gr_slot_origin_X (is) * xscale) - curradvx);+ pPos->y_offset = hb_clamp_to<hb_position_t> ((double) (gr_slot_origin_Y (is) * yscale) - curradvy);+ if (info->var2.u32 != curr_gr_cluster) {pPos->x_advance = info->var1.i32;- curradvx += pPos->x_advance;- currclus = info->cluster;+ curradvx = hb_saturate_add (curradvx, pPos->x_advance);+ curr_gr_cluster = info->var2.u32;} elsepPos->x_advance = 0.;- pPos->y_advance = gr_slot_advance_Y (is, grface, nullptr) * yscale;- curradvy += pPos->y_advance;+ pPos->y_advance = hb_clamp_to<hb_position_t> (gr_slot_advance_Y (is, grface, nullptr) * yscale);+ curradvy = hb_saturate_add (curradvy, pPos->y_advance);}}else{- curradvx = gr_seg_advance_X(seg) * xscale;+ curradvx = hb_clamp_to<hb_position_t> (gr_seg_advance_X(seg) * xscale);for (is = gr_seg_first_slot (seg); is; pPos++, info++, is = gr_slot_next_in_segment (is)){- if (info->cluster != currclus)+ if (info->var2.u32 != curr_gr_cluster){pPos->x_advance = info->var1.i32;- curradvx -= pPos->x_advance;- currclus = info->cluster;+ curradvx = hb_saturate_sub (curradvx, pPos->x_advance);+ curr_gr_cluster = info->var2.u32;} elsepPos->x_advance = 0.;- pPos->y_advance = gr_slot_advance_Y (is, grface, nullptr) * yscale;- curradvy -= pPos->y_advance;- pPos->x_offset = gr_slot_origin_X (is) * xscale - info->var1.i32 - curradvx + pPos->x_advance;- pPos->y_offset = gr_slot_origin_Y (is) * yscale - curradvy;+ pPos->y_advance = hb_clamp_to<hb_position_t> (gr_slot_advance_Y (is, grface, nullptr) * yscale);+ curradvy = hb_saturate_sub (curradvy, pPos->y_advance);+ pPos->x_offset = hb_clamp_to<hb_position_t> ((double) (gr_slot_origin_X (is) * xscale) -+ info->var1.i32 - curradvx + pPos->x_advance);+ pPos->y_offset = hb_clamp_to<hb_position_t> ((double) (gr_slot_origin_Y (is) * yscale) - curradvy);}hb_buffer_reverse_clusters (buffer);}diff --git a/thirdparty/harfbuzz/src/hb-iter.hh b/thirdparty/harfbuzz/src/hb-iter.hhindex ecc30f4e14c..19866863ce1 100644--- a/thirdparty/harfbuzz/src/hb-iter.hh+++ b/thirdparty/harfbuzz/src/hb-iter.hh@@ -460,7 +460,22 @@ struct hb_filter_iter_t :__item_t__ __item__ () const { return *it; }bool __more__ () const { return bool (it); }void __next__ () { do ++it; while (it && !hb_has (p.get (), hb_get (f.get (), *it))); }- void __prev__ () { do --it; while (it && !hb_has (p.get (), hb_get (f.get (), *it))); }+ void __prev__ ()+ {+ unsigned count = 0;+ do+ {+ Iter old = it;+ --it;+ if (!(it != old))+ {+ it += count;+ return;+ }+ count++;+ }+ while (!hb_has (p.get (), hb_get (f.get (), *it)));+ }hb_filter_iter_t __end__ () const { return hb_filter_iter_t (it._end (), p, f); }bool operator != (const hb_filter_iter_t& o) const{ return it != o.it; }diff --git a/thirdparty/harfbuzz/src/hb-kern.hh b/thirdparty/harfbuzz/src/hb-kern.hhindex e1ebf90742d..ce93acbeda9 100644--- a/thirdparty/harfbuzz/src/hb-kern.hh+++ b/thirdparty/harfbuzz/src/hb-kern.hh@@ -43,7 +43,6 @@ struct hb_kern_machine_tdriver (driver_),crossStream (crossStream_) {}- HB_NO_SANITIZE_SIGNED_INTEGER_OVERFLOWvoid kern (hb_font_t *font,hb_buffer_t *buffer,hb_mask_t kern_mask,@@ -72,9 +71,9 @@ struct hb_kern_machine_tskippy_iter.reset_fast (idx);unsigned unsafe_to;- if (!skippy_iter.next (&unsafe_to))+ if (unlikely (!skippy_iter.next (&unsafe_to))){- idx++;+ idx = unsafe_to;continue;}@@ -101,9 +100,9 @@ struct hb_kern_machine_t{hb_position_t kern1 = kern >> 1;hb_position_t kern2 = kern - kern1;- pos[i].x_advance += kern1;- pos[j].x_advance += kern2;- pos[j].x_offset += kern2;+ pos[i].x_advance = hb_saturate_add (pos[i].x_advance, kern1);+ pos[j].x_advance = hb_saturate_add (pos[j].x_advance, kern2);+ pos[j].x_offset = hb_saturate_add (pos[j].x_offset, kern2);}}else@@ -119,9 +118,9 @@ struct hb_kern_machine_t{hb_position_t kern1 = kern >> 1;hb_position_t kern2 = kern - kern1;- pos[i].y_advance += kern1;- pos[j].y_advance += kern2;- pos[j].y_offset += kern2;+ pos[i].y_advance = hb_saturate_add (pos[i].y_advance, kern1);+ pos[j].y_advance = hb_saturate_add (pos[j].y_advance, kern2);+ pos[j].y_offset = hb_saturate_add (pos[j].y_offset, kern2);}}diff --git a/thirdparty/harfbuzz/src/hb-limits.hh b/thirdparty/harfbuzz/src/hb-limits.hhindex 9d6c7ec6822..dcc624e8833 100644--- a/thirdparty/harfbuzz/src/hb-limits.hh+++ b/thirdparty/harfbuzz/src/hb-limits.hh@@ -58,6 +58,10 @@#define HB_MAX_CONTEXT_LENGTH 64#endif+#ifndef HB_MAX_SYLLABLE_LENGTH+#define HB_MAX_SYLLABLE_LENGTH 64+#endif+#ifndef HB_CLOSURE_MAX_STAGES/** The maximum number of times a lookup can be applied during shaping.@@ -81,7 +85,7 @@#endif#ifndef HB_MAX_FEATURE_INDICES-#define HB_MAX_FEATURE_INDICES 1500+#define HB_MAX_FEATURE_INDICES 8000#endif#ifndef HB_MAX_LOOKUP_VISIT_COUNT@@ -89,7 +93,7 @@#endif#ifndef HB_MAX_GRAPH_EDGE_COUNT-#define HB_MAX_GRAPH_EDGE_COUNT 2048+#define HB_MAX_GRAPH_EDGE_COUNT 16384#endif#ifndef HB_VAR_COMPOSITE_MAX_AXES@@ -116,6 +120,15 @@#define HB_GPU_DRAW_MAX_CURVES 65536#endif+/* Tiles emitted by one hb_paint_sweep_gradient_tiles() call. Also+ * sets the angular resolution (2π over this) below which a repeating+ * color line is filled with its average color instead of tiled;+ * a repeat/reflect color line whose stops span a tiny angle could+ * otherwise emit millions of patches while covering 0..2π. */+#ifndef HB_PAINT_MAX_SWEEP_TILES+#define HB_PAINT_MAX_SWEEP_TILES 4096+#endif+#ifndef HB_SVG_MAX_DOCUMENT_SIZE#define HB_SVG_MAX_DOCUMENT_SIZE ((size_t) 16 << 20)#endif@@ -124,17 +137,95 @@#define HB_RASTER_MAX_BUFFER_SIZE ((size_t) 1 << 30)#endif+/* Maximum surface dimension (pixels per side) when extents are derived+ * from font data (glyph extents or accumulated outline bounds). Bounds+ * attacker-controlled allocations; extents set explicitly through+ * hb_raster_{draw,paint}_set_extents() are not limited. */+#ifndef HB_RASTER_MAX_AUTO_DIMENSION+#define HB_RASTER_MAX_AUTO_DIMENSION 4096+#endif++/*+ * Cumulative work budgets.+ *+ * The limits above bound work within one subsystem: points per glyf+ * glyph, ops per CFF charstring, nodes in a COLR or VARC graph,+ * pixels per raster surface. When one subsystem drives another --+ * COLR driving a paint backend, a paint backend or VARC loading+ * glyf/CFF outlines -- those limits multiply. Each driving session+ * therefore carries one cumulative budget, initialized once per+ * top-level entry and only ever decremented, shared by everything+ * the session consumes. Once a budget is exhausted, further work+ * is skipped best-effort.+ */++/* One VARC glyph (draw or extents), shared by all leaf glyphs loaded+ * from glyf/CFF/CFF2, in units of glyf points / CFF charstring ops. */+#ifndef HB_VARC_MAX_WORK+#define HB_VARC_MAX_WORK ((int64_t) 1 << 20)+#endif++/* One paint-extents session, in outline points consumed by+ * clip-glyph draws. */+#ifndef HB_PAINT_EXTENTS_MAX_WORK+#define HB_PAINT_EXTENTS_MAX_WORK ((int64_t) 1 << 20)+#endif++/* One GPU paint walk, in curves consumed by clip encodes. */+#ifndef HB_GPU_PAINT_MAX_WORK+#define HB_GPU_PAINT_MAX_WORK ((int64_t) 1 << 20)+#endif++/* One vector (SVG/PDF) draw session, in bytes of generated outline+ * path data. */+#ifndef HB_VECTOR_MAX_DRAW_WORK+#define HB_VECTOR_MAX_DRAW_WORK ((int64_t) 16 << 20)+#endif++/* One vector (SVG/PDF) paint session, in bytes of generated outline+ * path and sweep-gradient patch data. */+#ifndef HB_VECTOR_MAX_PAINT_WORK+#define HB_VECTOR_MAX_PAINT_WORK ((int64_t) 16 << 20)+#endif++/* One raster paint session (everything painted between two+ * render/clear calls), in pixel-op units; pixel loops charge their+ * area, consumed outline segments are charged with a fixed weight.+ * The session budget is the larger of this flat value and+ * HB_RASTER_MAX_PAINT_WORK_PASSES full-surface passes, so very large+ * surfaces still get a few full-surface operations. */+#ifndef HB_RASTER_MAX_PAINT_WORK+#define HB_RASTER_MAX_PAINT_WORK ((int64_t) 1 << 26)+#endif++#ifndef HB_RASTER_MAX_PAINT_WORK_PASSES+#define HB_RASTER_MAX_PAINT_WORK_PASSES 4+#endif++/* One raster draw session (everything drawn between two render/clear+ * calls) through the standalone hb-raster-draw API, in Bézier+ * subdivision steps. When driven by raster-paint, the paint session+ * budget above is charged instead. */+#ifndef HB_RASTER_MAX_DRAW_WORK+#define HB_RASTER_MAX_DRAW_WORK ((int64_t) 1 << 24)+#endif++/* One raster draw session, in accumulated non-horizontal edges. */+#ifndef HB_RASTER_MAX_DRAW_EDGES+#define HB_RASTER_MAX_DRAW_EDGES ((int64_t) 1 << 20)+#endif+#ifndef HB_REPACKER_MAX_ITERATIONS#define HB_REPACKER_MAX_ITERATIONS 500#endif#ifndef HB_REPACKER_MAX_VERTICES-#define HB_REPACKER_MAX_VERTICES 100000+#define HB_REPACKER_MAX_VERTICES 800000#endif#ifndef HB_REPACKER_MAX_SPACES-#define HB_REPACKER_MAX_SPACES 1024+#define HB_REPACKER_MAX_SPACES 8000#endifdiff --git a/thirdparty/harfbuzz/src/hb-map.hh b/thirdparty/harfbuzz/src/hb-map.hhindex 37cc2460bb4..6a5e160c6b0 100644--- a/thirdparty/harfbuzz/src/hb-map.hh+++ b/thirdparty/harfbuzz/src/hb-map.hh@@ -49,11 +49,16 @@ struct hb_hashmap_tvoid _copy (const hb_hashmap_t& o){+ if (unlikely (!o.successful))+ {+ successful = false;+ return;+ }if (unlikely (!o.mask)) return;if (hb_is_trivially_copy_assignable (item_t)){- items = (item_t *) hb_malloc (sizeof (item_t) * (o.mask + 1));+ items = (item_t *) hb_malloc2 ((o.mask + 1), sizeof (item_t));if (unlikely (!items)){successful = false;@@ -199,12 +204,20 @@ struct hb_hashmap_tbool alloc (unsigned new_population = 0){if (unlikely (!successful)) return false;+ if (unlikely (population > 0x3FFFFFFFu || new_population > 0x3FFFFFFFu))+ {+ // Population sizes >0x3FFFFFFF will result in power+ // being larger than 31, which in turn leads to a new size+ // that overflows u32.+ successful = false;+ return false;+ }if (new_population != 0 && (new_population + new_population / 2) < mask) return true;unsigned int power = hb_bit_storage (hb_max (hb_max ((unsigned) population, new_population) * 2, 4u));unsigned int new_size = 1u << power;- item_t *new_items = (item_t *) hb_malloc ((size_t) new_size * sizeof (item_t));+ item_t *new_items = (item_t *) hb_malloc2 ((size_t) new_size, sizeof (item_t));if (unlikely (!new_items)){successful = false;@@ -288,7 +301,7 @@ struct hb_hashmap_toccupancy++;population++;- if (unlikely (length > max_chain_length) && occupancy * 8 > mask)+ if (unlikely (length > max_chain_length) && occupancy > mask / 8)alloc (mask - 8); // This ensures we jump to next larger sizereturn true;diff --git a/thirdparty/harfbuzz/src/hb-open-file.hh b/thirdparty/harfbuzz/src/hb-open-file.hhindex 6a53a7eb31e..a1c6b4289ea 100644--- a/thirdparty/harfbuzz/src/hb-open-file.hh+++ b/thirdparty/harfbuzz/src/hb-open-file.hh@@ -88,7 +88,7 @@ typedef struct OpenTypeOffsetTableunsigned int *table_count, /* IN/OUT */hb_tag_t *table_tags /* OUT */) const{- if (table_count)+ if (table_count && table_tags){+ tables.as_array ().sub_array (start_offset, table_count)| hb_map (&TableRecord::tag)@@ -474,8 +474,8 @@ struct OpenTypeFontFilecase TrueTag:case Typ1Tag:case TrueTypeTag: return 1;- case TTCTag: return u.ttcHeader.get_face_count ();- case DFontTag: return u.rfHeader.get_face_count ();+ case TTCTag: hb_barrier (); return u.ttcHeader.get_face_count ();+ case DFontTag: hb_barrier (); return u.rfHeader.get_face_count ();default: return 0;}}@@ -490,9 +490,9 @@ struct OpenTypeFontFilecase CFFTag: /* All the non-collection tags */case TrueTag:case Typ1Tag:- case TrueTypeTag: return u.fontFace;- case TTCTag: return u.ttcHeader.get_face (i);- case DFontTag: return u.rfHeader.get_face (i, base_offset);+ case TrueTypeTag: hb_barrier (); return u.fontFace;+ case TTCTag: hb_barrier (); return u.ttcHeader.get_face (i);+ case DFontTag: hb_barrier (); return u.rfHeader.get_face (i, base_offset);default: return Null (OpenTypeFontFace);}}@@ -518,9 +518,9 @@ struct OpenTypeFontFilecase CFFTag: /* All the non-collection tags */case TrueTag:case Typ1Tag:- case TrueTypeTag: return_trace (u.fontFace.sanitize (c));- case TTCTag: return_trace (u.ttcHeader.sanitize (c));- case DFontTag: return_trace (u.rfHeader.sanitize (c));+ case TrueTypeTag: hb_barrier (); return_trace (u.fontFace.sanitize (c));+ case TTCTag: hb_barrier (); return_trace (u.ttcHeader.sanitize (c));+ case DFontTag: hb_barrier (); return_trace (u.rfHeader.sanitize (c));default: return_trace (true);}}diff --git a/thirdparty/harfbuzz/src/hb-open-type.hh b/thirdparty/harfbuzz/src/hb-open-type.hhindex 792101664fa..9c7133d4653 100644--- a/thirdparty/harfbuzz/src/hb-open-type.hh+++ b/thirdparty/harfbuzz/src/hb-open-type.hh@@ -564,7 +564,7 @@ struct UnsizedArrayOf}static size_t get_size (unsigned int len)- { return len * Type::static_size; }+ { return hb_unsigned_mul_saturate (len, Type::static_size); }template <typename T> operator T * () { return arrayZ; }template <typename T> operator const T * () const { return arrayZ; }@@ -726,7 +726,7 @@ struct ArrayOf}size_t get_size () const- { return len.static_size + len * Type::static_size; }+ { return hb_unsigned_mul_add_saturate (len, Type::static_size, len.static_size); }explicit operator bool () const { return len; }@@ -910,7 +910,7 @@ struct HeadlessArrayOfreturn arrayZ[i-1];}size_t get_size () const- { return lenP1.static_size + get_length () * Type::static_size; }+ { return hb_unsigned_mul_add_saturate (get_length (), Type::static_size, lenP1.static_size); }unsigned get_length () const { return lenP1 ? lenP1 - 1 : 0; }@@ -1004,7 +1004,7 @@ struct ArrayOfM1return arrayZ[i];}size_t get_size () const- { return lenM1.static_size + (lenM1 + 1) * Type::static_size; }+ { return hb_unsigned_mul_add_saturate (lenM1 + 1, Type::static_size, lenM1.static_size); }template <typename ...Ts>HB_ALWAYS_INLINE@@ -1198,7 +1198,7 @@ struct VarSizedBinSearchArrayOfunsigned int get_length () const{ return header.nUnits - last_is_terminator (); }size_t get_size () const- { return header.static_size + header.nUnits * header.unitSize; }+ { return hb_unsigned_mul_add_saturate (header.nUnits, header.unitSize, header.static_size); }template <typename ...Ts>HB_ALWAYS_INLINE@@ -1464,7 +1464,8 @@ struct CFFIndexsize_t get_size () const{if (count)- return min_size + offSize.static_size + offset_array_size () + (offset_at (count) - 1);+ return hb_unsigned_add_saturate (min_size, offSize.static_size,+ offset_array_size (), offset_at (count) - 1);return min_size; /* empty CFFIndex contains count only */}diff --git a/thirdparty/harfbuzz/src/hb-ot-cff-common.hh b/thirdparty/harfbuzz/src/hb-ot-cff-common.hhindex 1ee1f2874a5..72b2b01b39e 100644--- a/thirdparty/harfbuzz/src/hb-ot-cff-common.hh+++ b/thirdparty/harfbuzz/src/hb-ot-cff-common.hh@@ -202,7 +202,7 @@ struct FDSelect0 {{ return {fds[glyph], glyph + 1}; }size_t get_size (unsigned int num_glyphs) const- { return HBUINT8::static_size * num_glyphs; }+ { return hb_unsigned_mul_saturate (HBUINT8::static_size, num_glyphs); }HBUINT8 fds[HB_VAR_ARRAY];@@ -230,7 +230,7 @@ template <typename GID_TYPE, typename FD_TYPE>struct FDSelect3_4{size_t get_size () const- { return GID_TYPE::static_size * 2 + ranges.get_size (); }+ { return hb_unsigned_add_saturate ((size_t) GID_TYPE::static_size * 2, ranges.get_size ()); }bool sanitize (hb_sanitize_context_t *c, unsigned int fdcount) const{@@ -308,8 +308,8 @@ struct FDSelect{switch (format){- case 0: hb_barrier (); return format.static_size + u.format0.get_size (num_glyphs);- case 3: hb_barrier (); return format.static_size + u.format3.get_size ();+ case 0: hb_barrier (); return hb_unsigned_add_saturate (format.static_size, u.format0.get_size (num_glyphs));+ case 3: hb_barrier (); return hb_unsigned_add_saturate (format.static_size, u.format3.get_size ());default:return 0;}}diff --git a/thirdparty/harfbuzz/src/hb-ot-cff1-table.cc b/thirdparty/harfbuzz/src/hb-ot-cff1-table.ccindex 716e412f549..25f71cb3447 100644--- a/thirdparty/harfbuzz/src/hb-ot-cff1-table.cc+++ b/thirdparty/harfbuzz/src/hb-ot-cff1-table.cc@@ -364,7 +364,7 @@ struct cff1_path_procs_extents_t : path_procs_t<cff1_path_procs_extents_t, cff1_}};-static bool _get_bounds (const OT::cff1::accelerator_t *cff, hb_codepoint_t glyph, bounds_t &bounds, bool in_seac=false);+static bool _get_bounds (const OT::cff1::accelerator_t *cff, hb_codepoint_t glyph, bounds_t &bounds, bool in_seac=false, int64_t *budget = nullptr);struct cff1_cs_opset_extents_t : cff1_cs_opset_t<cff1_cs_opset_extents_t, cff1_extents_param_t, cff1_path_procs_extents_t>{@@ -391,7 +391,7 @@ struct cff1_cs_opset_extents_t : cff1_cs_opset_t<cff1_cs_opset_extents_t, cff1_e}};-bool _get_bounds (const OT::cff1::accelerator_t *cff, hb_codepoint_t glyph, bounds_t &bounds, bool in_seac)+bool _get_bounds (const OT::cff1::accelerator_t *cff, hb_codepoint_t glyph, bounds_t &bounds, bool in_seac, int64_t *budget){bounds.init ();if (unlikely (!cff->is_valid () || (glyph >= cff->num_glyphs))) return false;@@ -402,12 +402,12 @@ bool _get_bounds (const OT::cff1::accelerator_t *cff, hb_codepoint_t glyph, bounenv.set_in_seac (in_seac);cff1_cs_interpreter_t<cff1_cs_opset_extents_t, cff1_extents_param_t> interp (env);cff1_extents_param_t param (cff);- if (unlikely (!interp.interpret (param))) return false;+ if (unlikely (!interp.interpret (param, budget))) return false;bounds = param.bounds;return true;}-bool OT::cff1::accelerator_t::get_extents (hb_font_t *font, hb_codepoint_t glyph, hb_glyph_extents_t *extents) const+bool OT::cff1::accelerator_t::get_extents (hb_font_t *font, hb_codepoint_t glyph, hb_glyph_extents_t *extents, int64_t *budget) const{#ifdef HB_NO_OT_FONT_CFF/* XXX Remove check when this code moves to .hh file. */@@ -416,7 +416,7 @@ bool OT::cff1::accelerator_t::get_extents (hb_font_t *font, hb_codepoint_t glyphbounds_t bounds;- if (!_get_bounds (this, glyph, bounds))+ if (!_get_bounds (this, glyph, bounds, false, budget))return false;if (bounds.min.x >= bounds.max.x)@@ -426,8 +426,9 @@ bool OT::cff1::accelerator_t::get_extents (hb_font_t *font, hb_codepoint_t glyph}else{- extents->x_bearing = roundf (bounds.min.x.to_real ());- extents->width = roundf (bounds.max.x.to_real () - extents->x_bearing);+ double x_bearing = roundf (bounds.min.x.to_real ());+ extents->x_bearing = hb_clamp_to<hb_position_t> (x_bearing);+ extents->width = hb_clamp_to<hb_position_t> ((double) roundf (bounds.max.x.to_real ()) - x_bearing);}if (bounds.min.y >= bounds.max.y){@@ -436,8 +437,9 @@ bool OT::cff1::accelerator_t::get_extents (hb_font_t *font, hb_codepoint_t glyph}else{- extents->y_bearing = roundf (bounds.max.y.to_real ());- extents->height = roundf (bounds.min.y.to_real () - extents->y_bearing);+ double y_bearing = roundf (bounds.max.y.to_real ());+ extents->y_bearing = hb_clamp_to<hb_position_t> (y_bearing);+ extents->height = hb_clamp_to<hb_position_t> ((double) roundf (bounds.min.y.to_real ()) - y_bearing);}font->scale_glyph_extents (extents);@@ -515,7 +517,8 @@ struct cff1_path_procs_path_t : path_procs_t<cff1_path_procs_path_t, cff1_cs_int};static bool _get_path (const OT::cff1::accelerator_t *cff, hb_font_t *font, hb_codepoint_t glyph,- hb_draw_session_t &draw_session, bool in_seac = false, point_t *delta = nullptr);+ hb_draw_session_t &draw_session, bool in_seac = false, point_t *delta = nullptr,+ int64_t *budget = nullptr);struct cff1_cs_opset_path_t : cff1_cs_opset_t<cff1_cs_opset_path_t, cff1_path_param_t, cff1_path_procs_path_t>{@@ -539,7 +542,8 @@ struct cff1_cs_opset_path_t : cff1_cs_opset_t<cff1_cs_opset_path_t, cff1_path_pa};bool _get_path (const OT::cff1::accelerator_t *cff, hb_font_t *font, hb_codepoint_t glyph,- hb_draw_session_t &draw_session, bool in_seac, point_t *delta)+ hb_draw_session_t &draw_session, bool in_seac, point_t *delta,+ int64_t *budget){if (unlikely (!cff->is_valid () || (glyph >= cff->num_glyphs))) return false;@@ -549,7 +553,7 @@ bool _get_path (const OT::cff1::accelerator_t *cff, hb_font_t *font, hb_codepoinenv.set_in_seac (in_seac);cff1_cs_interpreter_t<cff1_cs_opset_path_t, cff1_path_param_t> interp (env);cff1_path_param_t param (cff, font, draw_session, delta);- if (unlikely (!interp.interpret (param))) return false;+ if (unlikely (!interp.interpret (param, budget))) return false;/* Let's end the path specially since it is called inside seac also */param.end_path ();@@ -557,14 +561,14 @@ bool _get_path (const OT::cff1::accelerator_t *cff, hb_font_t *font, hb_codepoinreturn true;}-bool OT::cff1::accelerator_t::get_path (hb_font_t *font, hb_codepoint_t glyph, hb_draw_session_t &draw_session) const+bool OT::cff1::accelerator_t::get_path (hb_font_t *font, hb_codepoint_t glyph, hb_draw_session_t &draw_session, int64_t *budget) const{#ifdef HB_NO_OT_FONT_CFF/* XXX Remove check when this code moves to .hh file. */return true;#endif- return _get_path (this, font, glyph, draw_session);+ return _get_path (this, font, glyph, draw_session, false, nullptr, budget);}struct get_seac_param_t@@ -591,12 +595,41 @@ struct cff1_cs_opset_seac_t : cff1_cs_opset_t<cff1_cs_opset_seac_t, get_seac_par}};+static bool+_cff1_charstring_may_end_in_seac (const hb_ubytes_t &str)+{+ if (unlikely (!str.length || str[str.length - 1] != OpCode_endchar))+ return false;++ unsigned int end = str.length - 1;+ if (!end) return false;++ unsigned int last = str[end - 1];++ /* Type 2 numbers are not self-synchronizing when read backwards.+ * Keep interpreting if any number encoding could end at endchar. */+ if (OpCode_OneByteIntFirst <= last && last <= OpCode_OneByteIntLast)+ return true;+ if (end >= 2 &&+ OpCode_TwoBytePosInt0 <= str[end - 2] &&+ str[end - 2] <= OpCode_TwoByteNegInt3)+ return true;+ if (end >= 3 && str[end - 3] == OpCode_shortint)+ return true;+ if (end >= 5 && str[end - 5] == OpCode_fixedcs)+ return true;++ /* A subroutine can leave the seac operands on the shared stack. */+ return last == OpCode_callsubr || last == OpCode_callgsubr;+}+bool OT::cff1::accelerator_subset_t::get_seac_components (hb_codepoint_t glyph, hb_codepoint_t *base, hb_codepoint_t *accent) const{if (unlikely (!is_valid () || (glyph >= num_glyphs))) return false;unsigned int fd = fdSelect->get_fd (glyph);const hb_ubytes_t str = (*charStrings)[glyph];+ if (unlikely (!_cff1_charstring_may_end_in_seac (str))) return false;cff1_cs_interp_env_t env (str, *this, fd);cff1_cs_interpreter_t<cff1_cs_opset_seac_t, get_seac_param_t> interp (env);get_seac_param_t param (this);diff --git a/thirdparty/harfbuzz/src/hb-ot-cff1-table.hh b/thirdparty/harfbuzz/src/hb-ot-cff1-table.hhindex 5b2357e7e43..c44eedca311 100644--- a/thirdparty/harfbuzz/src/hb-ot-cff1-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-cff1-table.hh@@ -28,6 +28,7 @@#define HB_OT_CFF1_TABLE_HH#include "hb-ot-cff-common.hh"+#include "hb-depend-data.hh"#include "hb-subset-cff-common.hh"#include "hb-draw.hh"#include "hb-paint.hh"@@ -236,14 +237,14 @@ struct Encodingsize_t get_size () const{- unsigned int size = min_size;+ size_t size = min_size;switch (table_format ()){- case 0: hb_barrier (); size += u.format0.get_size (); break;- case 1: hb_barrier (); size += u.format1.get_size (); break;+ case 0: hb_barrier (); size = hb_unsigned_add_saturate (size, u.format0.get_size ()); break;+ case 1: hb_barrier (); size = hb_unsigned_add_saturate (size, u.format1.get_size ()); break;}if (has_supplement ())- size += suppEncData ().get_size ();+ size = hb_unsigned_add_saturate (size, suppEncData ().get_size ());return size;}@@ -326,7 +327,7 @@ struct Charset0void collect_glyph_to_sid_map (glyph_to_sid_map_t *mapping, unsigned int num_glyphs) const{- mapping->resize_dirty (num_glyphs);+ if (!mapping->resize_dirty (num_glyphs)) return;for (hb_codepoint_t gid = 1; gid < num_glyphs; gid++)mapping->arrayZ[gid] = {sids[gid - 1], gid};}@@ -426,10 +427,12 @@ struct Charset1_2 {void collect_glyph_to_sid_map (glyph_to_sid_map_t *mapping, unsigned int num_glyphs) const{- mapping->resize_dirty (num_glyphs);+ if (!mapping->resize_dirty (num_glyphs)) return;+hb_codepoint_t gid = 1;if (gid >= num_glyphs)return;+for (unsigned i = 0;; i++){hb_codepoint_t sid = ranges[i].first;@@ -567,9 +570,9 @@ struct Charset{switch (format){- case 0: hb_barrier (); return min_size + u.format0.get_size (num_glyphs);- case 1: hb_barrier (); return min_size + u.format1.get_size (num_glyphs);- case 2: hb_barrier (); return min_size + u.format2.get_size (num_glyphs);+ case 0: hb_barrier (); return hb_unsigned_add_saturate (min_size, u.format0.get_size (num_glyphs));+ case 1: hb_barrier (); return hb_unsigned_add_saturate (min_size, u.format1.get_size (num_glyphs));+ case 2: hb_barrier (); return hb_unsigned_add_saturate (min_size, u.format2.get_size (num_glyphs));default:return 0;}}@@ -770,8 +773,7 @@ struct cff1_top_dict_opset_t : top_dict_opset_t<cff1_top_dict_val_t>{static void process_op (op_code_t op, cff1_top_dict_interp_env_t& env, cff1_top_dict_values_t& dictval){- cff1_top_dict_val_t val;- val.last_arg_offset = (env.last_offset-1) - dictval.opStart; /* offset to the last argument */+ cff1_top_dict_val_t val {};switch (op) {case OpCode_version:@@ -815,6 +817,9 @@ struct cff1_top_dict_opset_t : top_dict_opset_t<cff1_top_dict_val_t>dictval.nameSIDs[name_dict_values_t::ordering] = env.argStack.pop_uint ();dictval.nameSIDs[name_dict_values_t::registry] = env.argStack.pop_uint ();env.clear_args ();+ if (unlikely (env.in_error ())) return;+ assert (env.last_offset > dictval.opStart);+ val.last_arg_offset = (env.last_offset - 1) - dictval.opStart; /* offset to the last argument */break;case OpCode_Encoding:@@ -1463,8 +1468,8 @@ struct cff1return true;}- HB_INTERNAL bool get_extents (hb_font_t *font, hb_codepoint_t glyph, hb_glyph_extents_t *extents) const;- HB_INTERNAL bool get_path (hb_font_t *font, hb_codepoint_t glyph, hb_draw_session_t &draw_session) const;+ HB_INTERNAL bool get_extents (hb_font_t *font, hb_codepoint_t glyph, hb_glyph_extents_t *extents, int64_t *budget = nullptr) const;+ HB_INTERNAL bool get_path (hb_font_t *font, hb_codepoint_t glyph, hb_draw_session_t &draw_session, int64_t *budget = nullptr) const;private:struct gname_t@@ -1533,6 +1538,20 @@ struct cff1_accelerator_t : cff1::accelerator_t {struct cff1_subset_accelerator_t : cff1::accelerator_subset_t {cff1_subset_accelerator_t (hb_face_t *face) : cff1::accelerator_subset_t (face) {}++ void depend (hb_depend_data_builder_t *builder) const+ {+ if (!is_valid ()) return;+ for (hb_codepoint_t gid = 0; gid < num_glyphs; gid++)+ {+ hb_codepoint_t base_gid, accent_gid;+ if (get_seac_components (gid, &base_gid, &accent_gid))+ {+ builder->add_depend (gid, HB_TAG('C','F','F',' '), base_gid);+ builder->add_depend (gid, HB_TAG('C','F','F',' '), accent_gid);+ }+ }+ }};} /* namespace OT */diff --git a/thirdparty/harfbuzz/src/hb-ot-cff2-table.cc b/thirdparty/harfbuzz/src/hb-ot-cff2-table.ccindex 92742ba63f1..e3c4af9fcb6 100644--- a/thirdparty/harfbuzz/src/hb-ot-cff2-table.cc+++ b/thirdparty/harfbuzz/src/hb-ot-cff2-table.cc@@ -113,7 +113,8 @@ bool OT::cff2::accelerator_t::get_extents (hb_font_t *font,bool OT::cff2::accelerator_t::get_extents_at (hb_font_t *font,hb_codepoint_t glyph,hb_glyph_extents_t *extents,- hb_array_t<const int> coords) const+ hb_array_t<const int> coords,+ int64_t *budget) const{#ifdef HB_NO_OT_FONT_CFF/* XXX Remove check when this code moves to .hh file. */@@ -127,7 +128,7 @@ bool OT::cff2::accelerator_t::get_extents_at (hb_font_t *font,cff2_cs_interp_env_t<number_t> env (str, *this, fd, coords.arrayZ, coords.length);cff2_cs_interpreter_t<cff2_cs_opset_extents_t, cff2_extents_param_t, number_t> interp (env);cff2_extents_param_t param;- if (unlikely (!interp.interpret (param))) return false;+ if (unlikely (!interp.interpret (param, budget))) return false;if (param.min_x >= param.max_x){@@ -136,8 +137,9 @@ bool OT::cff2::accelerator_t::get_extents_at (hb_font_t *font,}else{- extents->x_bearing = roundf (param.min_x.to_real ());- extents->width = roundf (param.max_x.to_real () - extents->x_bearing);+ double x_bearing = roundf (param.min_x.to_real ());+ extents->x_bearing = hb_clamp_to<hb_position_t> (x_bearing);+ extents->width = hb_clamp_to<hb_position_t> ((double) roundf (param.max_x.to_real ()) - x_bearing);}if (param.min_y >= param.max_y){@@ -146,8 +148,9 @@ bool OT::cff2::accelerator_t::get_extents_at (hb_font_t *font,}else{- extents->y_bearing = roundf (param.max_y.to_real ());- extents->height = roundf (param.min_y.to_real () - extents->y_bearing);+ double y_bearing = roundf (param.max_y.to_real ());+ extents->y_bearing = hb_clamp_to<hb_position_t> (y_bearing);+ extents->height = hb_clamp_to<hb_position_t> ((double) roundf (param.min_y.to_real ()) - y_bearing);}font->scale_glyph_extents (extents);@@ -213,7 +216,7 @@ bool OT::cff2::accelerator_t::get_path (hb_font_t *font, hb_codepoint_t glyph, hfont->has_nonzero_coords ? font->num_coords : 0));}-bool OT::cff2::accelerator_t::get_path_at (hb_font_t *font, hb_codepoint_t glyph, hb_draw_session_t &draw_session, hb_array_t<const int> coords) const+bool OT::cff2::accelerator_t::get_path_at (hb_font_t *font, hb_codepoint_t glyph, hb_draw_session_t &draw_session, hb_array_t<const int> coords, int64_t *budget) const{#ifdef HB_NO_OT_FONT_CFF/* XXX Remove check when this code moves to .hh file. */@@ -227,7 +230,7 @@ bool OT::cff2::accelerator_t::get_path_at (hb_font_t *font, hb_codepoint_t glyphcff2_cs_interp_env_t<number_t> env (str, *this, fd, coords.arrayZ, coords.length);cff2_cs_interpreter_t<cff2_cs_opset_path_t, cff2_path_param_t, number_t> interp (env);cff2_path_param_t param (font, draw_session);- if (unlikely (!interp.interpret (param))) return false;+ if (unlikely (!interp.interpret (param, budget))) return false;return true;}diff --git a/thirdparty/harfbuzz/src/hb-ot-cff2-table.hh b/thirdparty/harfbuzz/src/hb-ot-cff2-table.hhindex 06186383543..ddbf66b4f39 100644--- a/thirdparty/harfbuzz/src/hb-ot-cff2-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-cff2-table.hh@@ -346,6 +346,12 @@ struct cff2_private_dict_opset_subset_t : dict_opset_tenv.clear_args ();break;+ case OpCode_vsindexdict:+ env.process_vsindex ();+ dictval.ivs = env.get_ivs ();+ env.clear_args ();+ break;+default:SUPER::process_op (op, env);if (!env.argStack.is_empty ()) return;@@ -531,9 +537,10 @@ struct cff2HB_INTERNAL bool get_extents_at (hb_font_t *font,hb_codepoint_t glyph,hb_glyph_extents_t *extents,- hb_array_t<const int> coords) const;+ hb_array_t<const int> coords,+ int64_t *budget = nullptr) const;HB_INTERNAL bool get_path (hb_font_t *font, hb_codepoint_t glyph, hb_draw_session_t &draw_session) const;- HB_INTERNAL bool get_path_at (hb_font_t *font, hb_codepoint_t glyph, hb_draw_session_t &draw_session, hb_array_t<const int> coords) const;+ HB_INTERNAL bool get_path_at (hb_font_t *font, hb_codepoint_t glyph, hb_draw_session_t &draw_session, hb_array_t<const int> coords, int64_t *budget = nullptr) const;};struct accelerator_subset_t : accelerator_templ_t<cff2_private_dict_opset_subset_t, cff2_private_dict_values_subset_t>diff --git a/thirdparty/harfbuzz/src/hb-ot-cmap-table.hh b/thirdparty/harfbuzz/src/hb-ot-cmap-table.hhindex 6765c557fff..91be90fe5f2 100644--- a/thirdparty/harfbuzz/src/hb-ot-cmap-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-cmap-table.hh@@ -658,6 +658,7 @@ struct CmapSubtableFormat4hb_codepoint_t gid = this->glyphIdArray[index];if (unlikely (!gid))continue;+ gid = (gid + this->idDelta[i]) & 0xFFFFu;unicodes->add (codepoint);mapping->set (codepoint, gid);}@@ -2058,7 +2059,7 @@ struct cmapthis->subtable_uvs = &Null (CmapSubtableFormat14);{const CmapSubtable *st = table->find_subtable (0, 5);- if (st && st->u.format.v == 14)+ if (st && st->u.format.v == 14 && hb_barrier ())subtable_uvs = &st->u.format14;}@@ -2140,6 +2141,7 @@ struct cmapbreak;case 4:{+ hb_barrier ();this->format4_accel.init (&subtable->u.format4,get_subtable_data_size (subtable));this->get_glyph_data = &this->format4_accel;diff --git a/thirdparty/harfbuzz/src/hb-ot-fetch.cc b/thirdparty/harfbuzz/src/hb-ot-fetch.ccnew file mode 100644index 00000000000..fa11f877b33--- /dev/null+++ b/thirdparty/harfbuzz/src/hb-ot-fetch.cc@@ -0,0 +1,105 @@+/*+ * Copyright © 2026 Khaled Hosny+ *+ * 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.+ */++#include "hb.hh"++#ifndef HB_NO_OT_FETCH++#include "hb-ot.h"++#include "hb-ot-head-table.hh"+#include "hb-ot-os2-table.hh"+#include "hb-ot-post-table.hh"++/**+ * SECTION:hb-ot-fetch+ * @title: hb-ot-fetch+ * @short_description: OpenType bit fields and numbers+ * @include: hb-ot.h+ *+ * Functions for fetching various bit fields and numbers scattered around+ * OpenType tables.+ *+ * These are raw table values, and many of them are legacy or unreliable, but+ * applications might need them for various legacy reasons.+ **/+++/**+ * hb_ot_fetch_bits:+ * @face: #hb_face_t to work upon+ * @tag: tag of the bit field to fetch+ *+ * Fetches a bit field of @face.+ *+ * Return value: the bit field, or zero if the font does not have it.+ *+ * Since: 14.3.0+ **/+uint32_t+hb_ot_fetch_bits (hb_face_t *face,+ hb_ot_bits_tag_t tag)+{+ switch ((unsigned) tag)+ {+ case HB_OT_BITS_TAG_FS_TYPE: return face->table.OS2->fsType;+ case HB_OT_BITS_TAG_FS_SELECTION: return face->table.OS2->fsSelection;+ case HB_OT_BITS_TAG_MAC_STYLE: return face->table.head->get_mac_style ();+ case HB_OT_BITS_TAG_IS_FIXED_PITCH: return face->table.post->table->isFixedPitch;+ case HB_OT_BITS_TAG_UNICODE_RANGE_1: return face->table.OS2->ulUnicodeRange[0];+ case HB_OT_BITS_TAG_UNICODE_RANGE_2: return face->table.OS2->ulUnicodeRange[1];+ case HB_OT_BITS_TAG_UNICODE_RANGE_3: return face->table.OS2->ulUnicodeRange[2];+ case HB_OT_BITS_TAG_UNICODE_RANGE_4: return face->table.OS2->ulUnicodeRange[3];+ case HB_OT_BITS_TAG_CODE_PAGE_RANGE_1: return face->table.OS2->v1 ().ulCodePageRange1;+ case HB_OT_BITS_TAG_CODE_PAGE_RANGE_2: return face->table.OS2->v1 ().ulCodePageRange2;+ default: return 0;+ }+}++/**+ * hb_ot_fetch_number:+ * @face: #hb_face_t to work upon+ * @tag: tag of the number to fetch+ *+ * Fetches a number of @face in font units.+ *+ * Return value: the number, or zero if the font does not have it.+ *+ * Since: 14.3.0+ **/+int32_t+hb_ot_fetch_number (hb_face_t *face,+ hb_ot_number_tag_t tag)+{+ switch ((unsigned) tag)+ {+ case HB_OT_NUMBER_TAG_FONT_X_MIN: return face->table.head->xMin;+ case HB_OT_NUMBER_TAG_FONT_Y_MIN: return face->table.head->yMin;+ case HB_OT_NUMBER_TAG_FONT_X_MAX: return face->table.head->xMax;+ case HB_OT_NUMBER_TAG_FONT_Y_MAX: return face->table.head->yMax;+ default: return 0;+ }+}++#endifdiff --git a/thirdparty/harfbuzz/src/hb-ot-fetch.h b/thirdparty/harfbuzz/src/hb-ot-fetch.hnew file mode 100644index 00000000000..76530937e61--- /dev/null+++ b/thirdparty/harfbuzz/src/hb-ot-fetch.h@@ -0,0 +1,101 @@+/*+ * Copyright © 2026 Khaled Hosny+ *+ * 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.+ */++#if !defined(HB_OT_H_IN) && !defined(HB_NO_SINGLE_HEADER_ERROR)+#error "Include <hb-ot.h> instead."+#endif++#ifndef HB_OT_FETCH_H+#define HB_OT_FETCH_H++#include "hb.h"++HB_BEGIN_DECLS++/**+ * hb_ot_bits_tag_t:+ * @HB_OT_BITS_TAG_FS_TYPE: `fsType` of the `OS/2` table.+ * @HB_OT_BITS_TAG_FS_SELECTION: `fsSelection` of the `OS/2` table.+ * @HB_OT_BITS_TAG_MAC_STYLE: `macStyle` of the `head` table.+ * @HB_OT_BITS_TAG_IS_FIXED_PITCH: `isFixedPitch` of the `post` table.+ * @HB_OT_BITS_TAG_UNICODE_RANGE_1: `ulUnicodeRange1` of the `OS/2` table.+ * @HB_OT_BITS_TAG_UNICODE_RANGE_2: `ulUnicodeRange2` of the `OS/2` table.+ * @HB_OT_BITS_TAG_UNICODE_RANGE_3: `ulUnicodeRange3` of the `OS/2` table.+ * @HB_OT_BITS_TAG_UNICODE_RANGE_4: `ulUnicodeRange4` of the `OS/2` table.+ * @HB_OT_BITS_TAG_CODE_PAGE_RANGE_1: `ulCodePageRange1` of the `OS/2` table.+ * @HB_OT_BITS_TAG_CODE_PAGE_RANGE_2: `ulCodePageRange2` of the `OS/2` table.+ *+ * Bit fields that can be fetched with hb_ot_fetch_bits().+ *+ * Since: 14.3.0+ **/+typedef enum {+ HB_OT_BITS_TAG_FS_TYPE = HB_TAG ('f','s','t','p'),+ HB_OT_BITS_TAG_FS_SELECTION = HB_TAG ('f','s','s','l'),+ HB_OT_BITS_TAG_MAC_STYLE = HB_TAG ('m','c','s','t'),+ HB_OT_BITS_TAG_IS_FIXED_PITCH = HB_TAG ('f','x','p','t'),+ HB_OT_BITS_TAG_UNICODE_RANGE_1 = HB_TAG ('u','r','n','1'),+ HB_OT_BITS_TAG_UNICODE_RANGE_2 = HB_TAG ('u','r','n','2'),+ HB_OT_BITS_TAG_UNICODE_RANGE_3 = HB_TAG ('u','r','n','3'),+ HB_OT_BITS_TAG_UNICODE_RANGE_4 = HB_TAG ('u','r','n','4'),+ HB_OT_BITS_TAG_CODE_PAGE_RANGE_1 = HB_TAG ('c','p','r','1'),+ HB_OT_BITS_TAG_CODE_PAGE_RANGE_2 = HB_TAG ('c','p','r','2'),++ /*< private >*/+ _HB_OT_BITS_TAG_MAX_VALUE = HB_TAG_MAX_SIGNED /*< skip >*/+} hb_ot_bits_tag_t;+++HB_EXTERN uint32_t+hb_ot_fetch_bits (hb_face_t *face,+ hb_ot_bits_tag_t tag);++/**+ * hb_ot_number_tag_t:+ * @HB_OT_NUMBER_TAG_FONT_X_MIN: `xMin` of the `head` table.+ * @HB_OT_NUMBER_TAG_FONT_Y_MIN: `yMin` of the `head` table.+ * @HB_OT_NUMBER_TAG_FONT_X_MAX: `xMax` of the `head` table.+ * @HB_OT_NUMBER_TAG_FONT_Y_MAX: `yMax` of the `head` table.+ *+ * Numbers that can be fetched with hb_ot_fetch_number().+ *+ * Since: 14.3.0+ **/+typedef enum {+ HB_OT_NUMBER_TAG_FONT_X_MIN = HB_TAG ('x','m','i','n'),+ HB_OT_NUMBER_TAG_FONT_Y_MIN = HB_TAG ('y','m','i','n'),+ HB_OT_NUMBER_TAG_FONT_X_MAX = HB_TAG ('x','m','a','x'),+ HB_OT_NUMBER_TAG_FONT_Y_MAX = HB_TAG ('y','m','a','x'),++ /*< private >*/+ _HB_OT_NUMBER_TAG_MAX_VALUE = HB_TAG_MAX_SIGNED /*< skip >*/+} hb_ot_number_tag_t;++HB_EXTERN int32_t+hb_ot_fetch_number (hb_face_t *face,+ hb_ot_number_tag_t tag);++HB_END_DECLS++#endif /* HB_OT_FETCH_H */diff --git a/thirdparty/harfbuzz/src/hb-ot-font.cc b/thirdparty/harfbuzz/src/hb-ot-font.ccindex f42f679df2e..d91ee7af286 100644--- a/thirdparty/harfbuzz/src/hb-ot-font.cc+++ b/thirdparty/harfbuzz/src/hb-ot-font.cc@@ -289,7 +289,7 @@ struct hb_ot_font_tvoid check_serial (hb_font_t *font) const{- int font_serial = font->serial_coords.get_acquire ();+ int font_serial = font->serial.get_acquire ();if (cached_serial.get_acquire () != font_serial){/* These caches are dependent on scale and synthetic settings.@@ -644,6 +644,8 @@ hb_ot_get_glyph_v_origins (hb_font_t *font,const hb_ot_font_t *ot_font = (const hb_ot_font_t *) font_data;const hb_ot_face_t *ot_face = ot_font->ot_face;+ ot_font->check_serial (font);+/* First, set all the x values to half the advance width. */font->get_glyph_h_advances (count,first_glyph, glyph_stride,diff --git a/thirdparty/harfbuzz/src/hb-ot-hdmx-table.hh b/thirdparty/harfbuzz/src/hb-ot-hdmx-table.hhindex 6ba918e2d70..53ce798022d 100644--- a/thirdparty/harfbuzz/src/hb-ot-hdmx-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-hdmx-table.hh@@ -42,7 +42,7 @@ namespace OT {struct DeviceRecord{static size_t get_size (unsigned count)- { return hb_ceil_to_4 (min_size + count * HBUINT8::static_size); }+ { return hb_ceil_to_4 (hb_unsigned_mul_add_saturate (count, HBUINT8::static_size, min_size)); }template<typename Iterator,hb_requires (hb_is_iterator (Iterator))>@@ -88,7 +88,7 @@ struct hdmxstatic constexpr hb_tag_t tableTag = HB_OT_TAG_hdmx;size_t get_size () const- { return min_size + numRecords * sizeDeviceRecord; }+ { return hb_unsigned_mul_add_saturate (numRecords, sizeDeviceRecord, min_size); }template<typename Iterator,hb_requires (hb_is_iterator (Iterator))>diff --git a/thirdparty/harfbuzz/src/hb-ot-head-table.hh b/thirdparty/harfbuzz/src/hb-ot-head-table.hhindex 4cb6c15c677..bb1482fda99 100644--- a/thirdparty/harfbuzz/src/hb-ot-head-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-head-table.hh@@ -99,6 +99,8 @@ struct headbool is_condensed () const { return macStyle & CONDENSED; }bool is_expanded () const { return macStyle & EXPANDED; }+ unsigned get_mac_style () const { return macStyle; }+bool sanitize (hb_sanitize_context_t *c) const{TRACE_SANITIZE (this);diff --git a/thirdparty/harfbuzz/src/hb-ot-kern-table.hh b/thirdparty/harfbuzz/src/hb-ot-kern-table.hhindex d042c880537..540cec6da32 100644--- a/thirdparty/harfbuzz/src/hb-ot-kern-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-kern-table.hh@@ -144,13 +144,13 @@ struct KernSubTableunsigned int subtable_type = get_type ();TRACE_DISPATCH (this, subtable_type);switch (subtable_type) {- case 0: return_trace (c->dispatch (u.format0));+ case 0: hb_barrier (); return_trace (c->dispatch (u.format0));#ifndef HB_NO_AAT_SHAPE- case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));+ case 1: hb_barrier (); return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));#endif- case 2: return_trace (c->dispatch (u.format2));+ case 2: hb_barrier (); return_trace (c->dispatch (u.format2));#ifndef HB_NO_AAT_SHAPE- case 3: return_trace (c->dispatch (u.format3, std::forward<Ts> (ds)...));+ case 3: hb_barrier (); return_trace (c->dispatch (u.format3, std::forward<Ts> (ds)...));#endifdefault: return_trace (c->default_return_value ());}@@ -161,10 +161,14 @@ struct KernSubTable{unsigned int subtable_type = get_type ();switch (subtable_type) {- case 0: u.format0.collect_glyphs (left_set, right_set, num_glyphs); return;- case 1: u.format1.collect_glyphs (left_set, right_set, num_glyphs); return;- case 2: u.format2.collect_glyphs (left_set, right_set, num_glyphs); return;- case 3: u.format3.collect_glyphs (left_set, right_set, num_glyphs); return;+ case 0: hb_barrier (); u.format0.collect_glyphs (left_set, right_set, num_glyphs); return;+#ifndef HB_NO_AAT_SHAPE+ case 1: hb_barrier (); u.format1.collect_glyphs (left_set, right_set, num_glyphs); return;+#endif+ case 2: hb_barrier (); u.format2.collect_glyphs (left_set, right_set, num_glyphs); return;+#ifndef HB_NO_AAT_SHAPE+ case 3: hb_barrier (); u.format3.collect_glyphs (left_set, right_set, num_glyphs); return;+#endifdefault: return;}}@@ -184,9 +188,13 @@ struct KernSubTableunion {KernSubTableHeader header;AAT::KerxSubTableFormat0<KernSubTableHeader> format0;+#ifndef HB_NO_AAT_SHAPEAAT::KerxSubTableFormat1<KernSubTableHeader> format1;+#endifAAT::KerxSubTableFormat2<KernSubTableHeader> format2;+#ifndef HB_NO_AAT_SHAPEKernSubTableFormat3<KernSubTableHeader> format3;+#endif} u;public:DEFINE_SIZE_MIN (KernSubTableHeader::static_size);@@ -352,9 +360,9 @@ struct kernunsigned int subtable_type = get_type ();TRACE_DISPATCH (this, subtable_type);switch (subtable_type) {- case 0: return_trace (c->dispatch (u.ot, std::forward<Ts> (ds)...));+ case 0: hb_barrier (); return_trace (c->dispatch (u.ot, std::forward<Ts> (ds)...));#ifndef HB_NO_AAT_SHAPE- case 1: return_trace (c->dispatch (u.aat, std::forward<Ts> (ds)...));+ case 1: hb_barrier (); return_trace (c->dispatch (u.aat, std::forward<Ts> (ds)...));#endifdefault: return_trace (c->default_return_value ());}diff --git a/thirdparty/harfbuzz/src/hb-ot-layout-base-table.hh b/thirdparty/harfbuzz/src/hb-ot-layout-base-table.hhindex 2470e7e2f3c..37065644666 100644--- a/thirdparty/harfbuzz/src/hb-ot-layout-base-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-layout-base-table.hh@@ -79,8 +79,12 @@ struct BaseCoordFormat2auto *out = c->serializer->embed (*this);if (unlikely (!out)) return_trace (false);+ hb_codepoint_t *new_gid;+ if (!c->plan->glyph_map->has (referenceGlyph, &new_gid))+ return_trace (false);+return_trace (c->serializer->check_assign (out->referenceGlyph,- c->plan->glyph_map->get (referenceGlyph),+ *new_gid,HB_SERIALIZE_ERROR_INT_OVERFLOW));}@@ -109,8 +113,8 @@ struct BaseCoordFormat3const Device &device = this+deviceTable;return HB_DIRECTION_IS_HORIZONTAL (direction)- ? font->em_scale_y (coordinate) + device.get_y_delta (font, var_store)- : font->em_scale_x (coordinate) + device.get_x_delta (font, var_store);+ ? hb_saturate_add (font->em_scale_y (coordinate), device.get_y_delta (font, var_store))+ : hb_saturate_add (font->em_scale_x (coordinate), device.get_x_delta (font, var_store));}void collect_variation_indices (hb_set_t& varidx_set /* OUT */) const@@ -139,10 +143,12 @@ struct BaseCoordFormat3return_trace (false);}}- return_trace (out->deviceTable.serialize_copy (c->serializer, deviceTable,- this, 0,- hb_serialize_context_t::Head,- &c->plan->base_variation_idx_map));++ out->deviceTable.serialize_copy (c->serializer, deviceTable,+ this, 0,+ hb_serialize_context_t::Head,+ &c->plan->base_variation_idx_map);+ return_trace (true);}bool sanitize (hb_sanitize_context_t *c) const@@ -255,10 +261,10 @@ struct FeatMinMaxRecordTRACE_SUBSET (this);auto *out = c->serializer->embed (*this);if (unlikely (!out)) return_trace (false);- if (!(out->minCoord.serialize_subset (c, minCoord, base)))- return_trace (false);- return_trace (out->maxCoord.serialize_subset (c, maxCoord, base));+ bool ret = out->minCoord.serialize_subset (c, minCoord, base);+ ret |= out->maxCoord.serialize_subset (c, maxCoord, base);+ return_trace (ret);}bool sanitize (hb_sanitize_context_t *c, const void *base) const@@ -315,9 +321,8 @@ struct MinMaxauto *out = c->serializer->start_embed (*this);if (unlikely (!out || !c->serializer->extend_min (out))) return_trace (false);- if (!(out->minCoord.serialize_subset (c, minCoord, this)) ||- !(out->maxCoord.serialize_subset (c, maxCoord, this)))- return_trace (false);+ bool ret = out->minCoord.serialize_subset (c, minCoord, this);+ ret |= out->maxCoord.serialize_subset (c, maxCoord, this);unsigned len = 0;for (const FeatMinMaxRecord& _ : featMinMaxRecords)@@ -326,9 +331,13 @@ struct MinMaxif (!c->plan->layout_features.has (feature_tag))continue;- if (!_.subset (c, this)) return false;- len++;+ auto snap = c->serializer->snapshot ();+ if (!_.subset (c, this)) c->serializer->revert (snap);+ else len++;}++ if (len > 0) ret = true;+ if (!ret) return_trace (false);return_trace (c->serializer->check_assign (out->featMinMaxRecords.len, len,HB_SERIALIZE_ERROR_INT_OVERFLOW));}@@ -380,11 +389,15 @@ struct BaseValuesif (unlikely (!out || !c->serializer->extend_min (out))) return_trace (false);out->defaultIndex = defaultIndex;+ bool ret = false;for (const auto& _ : baseCoords)- if (!subset_offset_array (c, out->baseCoords, this) (_))- return_trace (false);+ {+ auto *o = out->baseCoords.serialize_append (c->serializer);+ if (unlikely (!o)) return_trace (false);+ ret |= o->serialize_subset (c, _, this);+ }- return_trace (bool (out->baseCoords));+ return_trace (ret);}bool sanitize (hb_sanitize_context_t *c) const@@ -478,16 +491,22 @@ struct BaseScriptauto *out = c->serializer->start_embed (*this);if (unlikely (!out || !c->serializer->extend_min (out))) return_trace (false);- if (baseValues && !out->baseValues.serialize_subset (c, baseValues, this))- return_trace (false);-- if (defaultMinMax && !out->defaultMinMax.serialize_subset (c, defaultMinMax, this))- return_trace (false);+ bool ret = out->baseValues.serialize_subset (c, baseValues, this);+ ret |= out->defaultMinMax.serialize_subset (c, defaultMinMax, this);+ unsigned len = 0;for (const auto& _ : baseLangSysRecords)- if (!_.subset (c, this)) return_trace (false);+ {+ auto snap = c->serializer->snapshot ();+ if (_.subset (c, this)) {+ ret = true;+ len++;+ }+ else c->serializer->revert (snap);+ }- return_trace (c->serializer->check_assign (out->baseLangSysRecords.len, baseLangSysRecords.len,+ if (!ret) return_trace (false);+ return_trace (c->serializer->check_assign (out->baseLangSysRecords.len, len,HB_SERIALIZE_ERROR_INT_OVERFLOW));}@@ -594,9 +613,12 @@ struct BaseScriptListif (!c->plan->layout_scripts.has (script_tag))continue;- if (!_.subset (c, this)) return false;- len++;+ auto snap = c->serializer->snapshot ();+ if (!_.subset (c, this)) c->serializer->revert (snap);+ else len++;}++ if (!len) return_trace (false);return_trace (c->serializer->check_assign (out->baseScriptRecords.len, len,HB_SERIALIZE_ERROR_INT_OVERFLOW));}@@ -672,8 +694,9 @@ struct Axisauto *out = c->serializer->embed (*this);if (unlikely (!out)) return_trace (false);- out->baseTagList.serialize_copy (c->serializer, baseTagList, this);- return_trace (out->baseScriptList.serialize_subset (c, baseScriptList, this));+ bool ret = out->baseTagList.serialize_copy (c->serializer, baseTagList, this);+ ret |= out->baseScriptList.serialize_subset (c, baseScriptList, this);+ return_trace (ret);}bool sanitize (hb_sanitize_context_t *c) const@@ -770,13 +793,10 @@ struct BASEif (has_var_store () && !subset_varstore (c, out))return_trace (false);- if (hAxis && !out->hAxis.serialize_subset (c, hAxis, this))- return_trace (false);+ bool ret = out->hAxis.serialize_subset (c, hAxis, this);+ ret |= out->vAxis.serialize_subset (c, vAxis, this);- if (vAxis && !out->vAxis.serialize_subset (c, vAxis, this))- return_trace (false);-- return_trace (true);+ return_trace (ret);}bool get_baseline (hb_font_t *font,diff --git a/thirdparty/harfbuzz/src/hb-ot-layout-common.hh b/thirdparty/harfbuzz/src/hb-ot-layout-common.hhindex b07a4004697..45a257eb755 100644--- a/thirdparty/harfbuzz/src/hb-ot-layout-common.hh+++ b/thirdparty/harfbuzz/src/hb-ot-layout-common.hh@@ -441,7 +441,7 @@ struct IndexArray : Array16Of<Index>unsigned int *_count /* IN/OUT */,unsigned int *_indexes /* OUT */) const{- if (_count)+ if (_count && _indexes){+ this->as_array ().sub_array (start_offset, _count)| hb_sink (hb_array (_indexes, *_count))@@ -628,7 +628,7 @@ struct FeatureParamsCharacterVariantsunsignedget_characters (unsigned start_offset, unsigned *char_count, hb_codepoint_t *chars) const{- if (char_count)+ if (char_count && chars){+ characters.as_array ().sub_array (start_offset, char_count)| hb_sink (hb_array (chars, *char_count))@@ -638,7 +638,7 @@ struct FeatureParamsCharacterVariants}size_t get_size () const- { return min_size + characters.len * HBUINT24::static_size; }+ { return hb_unsigned_mul_add_saturate (characters.len, HBUINT24::static_size, min_size); }void collect_name_ids (hb_set_t *nameids_to_retain /* OUT */) const{@@ -706,7 +706,7 @@ struct FeatureParamsreturn true;#endifTRACE_SANITIZE (this);- if (tag == HB_TAG ('s','i','z','e'))+ if (tag == HB_TAG ('s','i','z','e') && hb_barrier ())return_trace (u.size.sanitize (c));if ((tag & 0xFFFF0000u) == HB_TAG ('s','s','\0','\0')) /* ssXX */return_trace (u.stylisticSet.sanitize (c));@@ -720,7 +720,7 @@ struct FeatureParams#ifdef HB_NO_LAYOUT_FEATURE_PARAMSreturn;#endif- if (tag == HB_TAG ('s','i','z','e'))+ if (tag == HB_TAG ('s','i','z','e') && hb_barrier ())return (u.size.collect_name_ids (nameids_to_retain));if ((tag & 0xFFFF0000u) == HB_TAG ('s','s','\0','\0')) /* ssXX */return (u.stylisticSet.collect_name_ids (nameids_to_retain));@@ -732,7 +732,7 @@ struct FeatureParams{TRACE_SUBSET (this);if (!tag) return_trace (false);- if (*tag == HB_TAG ('s','i','z','e'))+ if (*tag == HB_TAG ('s','i','z','e') && hb_barrier ())return_trace (u.size.subset (c));if ((*tag & 0xFFFF0000u) == HB_TAG ('s','s','\0','\0')) /* ssXX */return_trace (u.stylisticSet.subset (c));@@ -744,7 +744,7 @@ struct FeatureParams#ifndef HB_NO_LAYOUT_FEATURE_PARAMSconst FeatureParamsSize& get_size_params (hb_tag_t tag) const{- if (tag == HB_TAG ('s','i','z','e'))+ if (tag == HB_TAG ('s','i','z','e') && hb_barrier ())return u.size;return Null (FeatureParamsSize);}@@ -900,7 +900,7 @@ struct RecordArrayOf : SortedArray16Of<Record<Type>>unsigned int *record_count /* IN/OUT */,hb_tag_t *record_tags /* OUT */) const{- if (record_count)+ if (record_count && record_tags){+ this->as_array ().sub_array (start_offset, record_count)| hb_map (&Record<Type>::tag)@@ -1551,7 +1551,6 @@ struct ClassDefFormat1_3const Coverage* glyph_filter = nullptr) const{TRACE_SUBSET (this);- const hb_map_t &glyph_map = c->plan->glyph_map_gsub;hb_sorted_vector_t<hb_codepoint_pair_t> glyph_and_klass;hb_set_t orig_klasses;@@ -1561,7 +1560,7 @@ struct ClassDefFormat1_3for (const hb_codepoint_t gid : + hb_range (start, end)){- hb_codepoint_t new_gid = glyph_map[gid];+ hb_codepoint_t new_gid = c->plan->map_gsub_glyph (gid);if (new_gid == HB_MAP_VALUE_INVALID) continue;if (glyph_filter && !glyph_filter->has(gid)) continue;@@ -1574,9 +1573,10 @@ struct ClassDefFormat1_3if (use_class_zero){+ const hb_set_t& glyphset = *c->plan->glyphset_gsub ();unsigned glyph_count = glyph_filter- ? hb_len (hb_iter (glyph_map.keys()) | hb_filter (glyph_filter))- : glyph_map.get_population ();+ ? hb_len (hb_iter (glyphset) | hb_filter (glyph_filter))+ : glyphset.get_population ();use_class_zero = glyph_count <= glyph_and_klass.length;}if (!ClassDef_remap_and_serialize (c->serializer,@@ -1810,7 +1810,6 @@ struct ClassDefFormat2_4const Coverage* glyph_filter = nullptr) const{TRACE_SUBSET (this);- const hb_map_t &glyph_map = c->plan->glyph_map_gsub;const hb_set_t &glyph_set = *c->plan->glyphset_gsub ();hb_sorted_vector_t<hb_codepoint_pair_t> glyph_and_klass;@@ -1823,7 +1822,7 @@ struct ClassDefFormat2_4{unsigned klass = get_class (g);if (!klass) continue;- hb_codepoint_t new_gid = glyph_map[g];+ hb_codepoint_t new_gid = c->plan->map_gsub_glyph (g);if (new_gid == HB_MAP_VALUE_INVALID) continue;if (glyph_filter && !glyph_filter->has (g)) continue;glyph_and_klass.push (hb_pair (new_gid, klass));@@ -1841,7 +1840,7 @@ struct ClassDefFormat2_4hb_codepoint_t end = hb_min (range.last + 1, num_source_glyphs);for (hb_codepoint_t g = start; g < end; g++){- hb_codepoint_t new_gid = glyph_map[g];+ hb_codepoint_t new_gid = c->plan->map_gsub_glyph (g);if (new_gid == HB_MAP_VALUE_INVALID) continue;if (glyph_filter && !glyph_filter->has (g)) continue;@@ -1854,7 +1853,7 @@ struct ClassDefFormat2_4const hb_set_t& glyphset = *c->plan->glyphset_gsub ();unsigned glyph_count = glyph_filter? hb_len (hb_iter (glyphset) | hb_filter (glyph_filter))- : glyph_map.get_population ();+ : glyphset.get_population ();use_class_zero = use_class_zero && glyph_count <= glyph_and_klass.length;if (!ClassDef_remap_and_serialize (c->serializer,orig_klasses,@@ -2633,8 +2632,9 @@ struct hb_scalar_cache_t*cached_value = roundf(value * MULTIPLIER);}- private:+ public:unsigned length;+ private:mutable hb_atomic_t<int> static_values[STATIC_LENGTH];};@@ -2791,7 +2791,10 @@ struct VarRegionListreturn !regions.in_error ();}- size_t get_size () const { return min_size + VarRegionAxis::static_size * axisCount * regionCount; }+ size_t get_size () const+ { return hb_unsigned_add_saturate (min_size,+ hb_unsigned_mul_saturate (VarRegionAxis::static_size,+ axisCount, regionCount)); }public:HBUINT16 axisCount;@@ -2803,6 +2806,40 @@ struct VarRegionListDEFINE_SIZE_ARRAY (4, axesZ);};+/* Whether a variation region is unreachable given per-axis reachable+ * final-coordinate ranges, in F2Dot14 units (avar2 partial-instancing+ * culling; see hb_subset_plan_t::avar2_reachable_ranges). A region is dead+ * if some axis's tent evaluates to zero over the axis's entire reachable+ * range. Mirrors the runtime evaluation: invalid tents evaluate as+ * constant 1 and never kill a region. */+static inline bool+_hb_avar2_region_is_dead (const hb_hashmap_t<hb_tag_t, Triple> &axis_tuples,+ const hb_hashmap_t<hb_tag_t, Triple> &reachable_ranges)+{+ for (auto _ : axis_tuples)+ {+ Triple *range;+ if (!reachable_ranges.has (_.first, &range)) continue;+ const Triple &tent = _.second;+ int start = (int) roundf ((float) tent.minimum * 16384.f);+ int peak = (int) roundf ((float) tent.middle * 16384.f);+ int end = (int) roundf ((float) tent.maximum * 16384.f);+ if (!peak) continue;+ if (start > peak || peak > end) continue;+ if (start < 0 && end > 0) continue;+ int lo = (int) roundf ((float) range->minimum * 16384.f);+ int hi = (int) roundf ((float) range->maximum * 16384.f);+ /* Strict comparisons: the scalar is 1 (not 0) at v == peak, so a tent+ * whose peak sits exactly on the range boundary is still live there.+ * (Reachable ranges are padded by one F2Dot14 unit at their producer,+ * which already covers this; strictness keeps the predicate correct on+ * its own terms.) */+ if (hi < start || lo > end)+ return true;+ }+ return false;+}+struct SparseVariationRegion : Array16Of<SparseVarRegionAxis>{float evaluate (const int *coords, unsigned int coord_len) const@@ -2868,14 +2905,13 @@ struct VarDataunsigned get_region_index (unsigned i) const{ return i >= regionIndices.len ? -1 : regionIndices[i]; }- unsigned int get_row_size () const+ size_t get_row_size () const{ return (wordCount () + regionIndices.len) * (longWords () ? 2 : 1); }size_t get_size () const- { return min_size- - regionIndices.min_size + regionIndices.get_size ()- + itemCount * get_row_size ();- }+ { return hb_unsigned_add_saturate (min_size - regionIndices.min_size,+ regionIndices.get_size (),+ hb_unsigned_mul_saturate (itemCount, get_row_size ())); }float _get_delta (unsigned int inner,const int *coords, unsigned int coord_count,@@ -3044,7 +3080,8 @@ struct VarDatabool serialize (hb_serialize_context_t *c,const VarData *src,const hb_inc_bimap_t &inner_map,- const hb_inc_bimap_t ®ion_map)+ const hb_inc_bimap_t ®ion_map,+ const hb_set_t *culled_regions = nullptr){TRACE_SERIALIZE (this);if (unlikely (!c->extend_min (this))) return_trace (false);@@ -3089,6 +3126,8 @@ struct VarDatabool short_circuit = src_long_words == has_long && src_word_count <= r;delta_sz[r] = kZero;+ if (culled_regions && culled_regions->has (src->regionIndices[r]))+ continue; /* unreachable region: drop its column */for (unsigned old_gid : inner_map.keys()){int32_t delta = src->get_item_delta_fast (old_gid, r, src_delta_bytes, src_row_size);@@ -3244,10 +3283,9 @@ struct VarDatastruct MultiVarData{size_t get_size () const- { return min_size- - regionIndices.min_size + regionIndices.get_size ()- + StructAfter<CFF2Index> (regionIndices).get_size ();- }+ { return hb_unsigned_add_saturate (min_size - regionIndices.min_size,+ regionIndices.get_size (),+ StructAfter<CFF2Index> (regionIndices).get_size ()); }void get_delta (unsigned int inner,const int *coords, unsigned int coord_count,@@ -3335,6 +3373,18 @@ struct ItemVariationStore}public:+ bool has_delta_set (unsigned int index) const+ {+#ifdef HB_NO_VAR+ return false;+#endif++ unsigned int outer = index >> 16;+ unsigned int inner = index & 0xFFFF;+ return outer < dataSets.len &&+ inner < (this+dataSets[outer]).get_item_count ();+ }+float get_delta (unsigned int index,const int *coords, unsigned int coord_count,hb_scalar_cache_t *cache = nullptr) const@@ -3398,7 +3448,8 @@ struct ItemVariationStorebool serialize (hb_serialize_context_t *c,const ItemVariationStore *src,- const hb_array_t <const hb_inc_bimap_t> &inner_maps)+ const hb_array_t <const hb_inc_bimap_t> &inner_maps,+ const hb_set_t *culled_regions = nullptr){TRACE_SERIALIZE (this);#ifdef HB_NO_VAR@@ -3425,6 +3476,9 @@ struct ItemVariationStoreregion_indices.del_range ((src_regions).regionCount, hb_set_t::INVALID);+ if (culled_regions)+ region_indices.subtract (*culled_regions);+/* TODO use constructor when our data-structures support that. */hb_inc_bimap_t region_map;+ hb_iter (region_indices)@@ -3446,7 +3500,8 @@ struct ItemVariationStore{if (!inner_maps[i].get_population ()) continue;if (unlikely (!dataSets[set_index++]- .serialize_serialize (c, &(src+src->dataSets[i]), inner_maps[i], region_map)))+ .serialize_serialize (c, &(src+src->dataSets[i]), inner_maps[i], region_map,+ culled_regions)))return_trace (false);}@@ -3478,6 +3533,30 @@ struct ItemVariationStorereturn_trace (out);}+ /* Collect regions that a partial avar2 instance can never reach, per the+ * plan's reachable final-coordinate ranges. */+ bool collect_dead_regions (const hb_map_t &axes_old_index_tag_map,+ const hb_hashmap_t<hb_tag_t, Triple> &reachable_ranges,+ hb_set_t &dead_regions /* OUT */) const+ {+#ifndef HB_NO_VAR+ if (!reachable_ranges.get_population ()) return true;+ const VarRegionList ®ion_list = this+regions;+ unsigned count = region_list.regionCount;+ for (unsigned i = 0; i < count; i++)+ {+ hb_hashmap_t<hb_tag_t, Triple> axis_tuples;+ if (!region_list.get_var_region (i, axes_old_index_tag_map, axis_tuples))+ return false;+ if (_hb_avar2_region_is_dead (axis_tuples, reachable_ranges))+ dead_regions.add (i);+ }+ return !dead_regions.in_error ();+#else+ return true;+#endif+ }+bool subset (hb_subset_context_t *c, const hb_array_t<const hb_inc_bimap_t> &inner_maps) const{TRACE_SUBSET (this);@@ -3488,7 +3567,16 @@ struct ItemVariationStoreItemVariationStore *varstore_prime = c->serializer->start_embed<ItemVariationStore> ();if (unlikely (!varstore_prime)) return_trace (false);- varstore_prime->serialize (c->serializer, this, inner_maps);+ /* avar2 partial instancing: cull unreachable regions. */+ hb_set_t dead_regions;+ if (c->plan->has_avar2)+ if (!collect_dead_regions (c->plan->axes_old_index_tag_map,+ c->plan->avar2_reachable_ranges,+ dead_regions))+ return_trace (false);++ varstore_prime->serialize (c->serializer, this, inner_maps,+ dead_regions.get_population () ? &dead_regions : nullptr);return_trace (!c->serializer->in_error()@@ -3639,7 +3727,7 @@ struct DeltaSetIndexMapFormat01friend struct DeltaSetIndexMap;size_t get_size () const- { return min_size + mapCount * get_width (); }+ { return hb_unsigned_mul_add_saturate (mapCount, get_width (), min_size); }private:DeltaSetIndexMapFormat01* copy (hb_serialize_context_t *c) const@@ -4025,6 +4113,7 @@ struct ConditionAxisRangereturn filterRangeMinValue.to_int () <= coord && coord <= filterRangeMaxValue.to_int ();}+ public:bool sanitize (hb_sanitize_context_t *c) const{TRACE_SANITIZE (this);@@ -4070,6 +4159,7 @@ struct ConditionValuereturn_trace (false);}+ public:bool sanitize (hb_sanitize_context_t *c) const{TRACE_SANITIZE (this);@@ -4118,6 +4208,7 @@ struct ConditionAndreturn_trace (false);}+ public:bool sanitize (hb_sanitize_context_t *c) const{TRACE_SANITIZE (this);@@ -4165,6 +4256,7 @@ struct ConditionOrreturn_trace (false);}+ public:bool sanitize (hb_sanitize_context_t *c) const{TRACE_SANITIZE (this);@@ -4208,6 +4300,7 @@ struct ConditionNegatereturn_trace (false);}+ public:bool sanitize (hb_sanitize_context_t *c) const{TRACE_SANITIZE (this);@@ -4265,16 +4358,11 @@ struct Conditionbool sanitize (hb_sanitize_context_t *c) const{TRACE_SANITIZE (this);- if (!u.format.v.sanitize (c)) return_trace (false);- hb_barrier ();- switch (u.format.v) {- case 1: hb_barrier (); return_trace (u.format1.sanitize (c));- case 2: hb_barrier (); return_trace (u.format2.sanitize (c));- case 3: hb_barrier (); return_trace (u.format3.sanitize (c));- case 4: hb_barrier (); return_trace (u.format4.sanitize (c));- case 5: hb_barrier (); return_trace (u.format5.sanitize (c));- default:return_trace (true);- }++ if (unlikely (!c->check_start_recursion (HB_MAX_NESTING_LEVEL)))+ return_trace (c->no_dispatch_return_value ());++ return_trace (c->end_recursion (this->dispatch (c)));}protected:@@ -4657,6 +4745,11 @@ struct FeatureVariations{static constexpr unsigned NOT_FOUND_INDEX = 0xFFFFFFFFu;+ unsigned record_count () const+ {+ return varRecords.len;+ }+bool find_index (const int *coords, unsigned int coord_len,unsigned int *index,ItemVarStoreInstancer *instancer) const@@ -4953,10 +5046,12 @@ struct Device{#ifndef HB_NO_HINTINGcase 1: case 2: case 3:+ hb_barrier ();return u.hinting.get_x_delta (font);#endif#ifndef HB_NO_VARcase 0x8000:+ hb_barrier ();return u.variation.get_x_delta (font, store, store_cache);#endifdefault:@@ -4971,10 +5066,12 @@ struct Device{case 1: case 2: case 3:#ifndef HB_NO_HINTING+ hb_barrier ();return u.hinting.get_y_delta (font);#endif#ifndef HB_NO_VARcase 0x8000:+ hb_barrier ();return u.variation.get_y_delta (font, store, store_cache);#endifdefault:@@ -4989,10 +5086,12 @@ struct Deviceswitch (u.b.format) {#ifndef HB_NO_HINTINGcase 1: case 2: case 3:+ hb_barrier ();return_trace (u.hinting.sanitize (c));#endif#ifndef HB_NO_VARcase 0x8000:+ hb_barrier ();return_trace (u.variation.sanitize (c));#endifdefault:@@ -5009,10 +5108,12 @@ struct Devicecase 1:case 2:case 3:+ hb_barrier ();return_trace (reinterpret_cast<Device *> (u.hinting.copy (c)));#endif#ifndef HB_NO_VARcase 0x8000:+ hb_barrier ();return_trace (reinterpret_cast<Device *> (u.variation.copy (c, layout_variation_idx_delta_map)));#endifdefault:@@ -5031,6 +5132,7 @@ struct Device#endif#ifndef HB_NO_VARcase 0x8000:+ hb_barrier ();u.variation.collect_variation_index (c);return;#endif@@ -5044,6 +5146,7 @@ struct Deviceswitch (u.b.format) {#ifndef HB_NO_VARcase 0x8000:+ hb_barrier ();return u.variation.varIdx;#endifdefault:diff --git a/thirdparty/harfbuzz/src/hb-ot-layout-gsub-table.hh b/thirdparty/harfbuzz/src/hb-ot-layout-gsub-table.hhindex 8d5e1f18638..cc603e878c6 100644--- a/thirdparty/harfbuzz/src/hb-ot-layout-gsub-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-layout-gsub-table.hh@@ -58,6 +58,24 @@ template <typename context_t>return l.dispatch (c);}+/*static*/ hb_depend_context_t::return_t SubstLookup::depend_glyphs_recurse_func (hb_depend_context_t *c, unsigned lookup_index, hb_bit_page_t *covered_seq_indices, unsigned seq_index, unsigned end_index)+{+ const SubstLookup &l = c->face->table.GSUB.get_relaxed ()->table->get_lookup (lookup_index);+ /* After a non-1-to-1 lookup (expansion/contraction), subsequent lookups in the same+ * contextual rule see all glyphs, not position-specific ones. This matches closure behavior.+ * Mark sequence positions as covered so later lookups use the full glyph set. */+ if (l.may_have_non_1to1 ())+ covered_seq_indices->add_range (seq_index, end_index);++ hb_depend_context_t::recurse_key_t key;+ if (!c->get_recurse_key (lookup_index, &key))+ return hb_empty_t ();++ hb_depend_context_t::return_t ret = l.dispatch (c);+ c->finish_recurse (key);+ return ret;+}+template <>inline hb_closure_lookups_context_t::return_tSubstLookup::dispatch_recurse_func<hb_closure_lookups_context_t> (hb_closure_lookups_context_t *c, unsigned this_index)@@ -96,7 +114,90 @@ inline bool SubstLookup::dispatch_recurse_func<hb_ot_apply_context_t> (hb_ot_app} /* namespace GSUB_impl */} /* namespace Layout */-} /* namespace OT */+inline void+GSUB_accelerator_t::depend (hb_depend_data_builder_t *builder, hb_face_t *face) const+{+ if (!this->table->has_data ()) return;++ unsigned num_features = this->table->get_feature_count ();+ unsigned num_lookups = this->table->get_lookup_count ();++ hb_vector_t<hb_tag_t> feature_tags;+ if (!builder->check_success (feature_tags.resize (num_features)))+ return;+ this->table->get_feature_tags (0, &num_features, feature_tags.arrayZ);++ if (!builder->init_lookup_features (num_lookups))+ return;++ hb_vector_t<hb_tag_t> feature_query_v;+ feature_query_v.resize (2);+ feature_query_v[1] = 0;++ hb_set_t seen_features;+ hb_set_t feature_indexes, lookup_indexes;++ for (auto ft : feature_tags)+ {+ if (seen_features.has (ft)) continue;+ seen_features.add (ft);+ feature_query_v[0] = ft;+ feature_indexes.reset ();+ hb_ot_layout_collect_features (face, HB_OT_TAG_GSUB, nullptr, nullptr,+ feature_query_v.arrayZ, &feature_indexes);+ lookup_indexes.reset ();+ for (auto feature_index : feature_indexes)+ this->table->get_feature (feature_index).add_lookup_indexes_to (&lookup_indexes);++ for (auto lookup_index : lookup_indexes)+ if (unlikely (!builder->add_lookup_feature (lookup_index, ft)))+ return;++ auto &fv = this->table->get_feature_variations ();+ auto fi_count = fv.record_count ();+ for (unsigned i = 0; i < fi_count; i++)+ {+ lookup_indexes.reset ();+ for (auto feature_index : feature_indexes)+ {+ auto feature_ptr = fv.find_substitute (i, feature_index);+ if (feature_ptr != nullptr)+ feature_ptr->add_lookup_indexes_to (&lookup_indexes);+ }+ for (auto lookup_index : lookup_indexes)+ if (unlikely (!builder->add_lookup_feature (lookup_index, ft)))+ return;+ }+ }++ if (unlikely (!builder->finish_lookup_features ()))+ return;++ hb_set_t all_glyphs;+ all_glyphs.add_range (0, face->get_num_glyphs () - 1);++ hb_depend_context_t c (builder, face, &all_glyphs);++ for (unsigned i = 0; i < num_lookups; i++)+ {+ auto features = builder->get_lookup_features (i);+ if (!features)+ {+ DEBUG_MSG_LEVEL (DEPEND, nullptr, 1, 0,+ "Skipping lookup %u (no features)", i);+ continue;+ }+ DEBUG_MSG_LEVEL (DEPEND, nullptr, 1, 0,+ "Processing lookup %u with features:", i);+ c.lookup_index = i;+ c.reset_recurse_cache ();+ c.lookups_seen.clear ();+ c.lookups_seen.add (i); /* Seed for A→B→A cycle detection in recurse(). */+ this->table->get_lookup (i).depend (&c);+ }+}++} /* namespace OT */#endif /* HB_OT_LAYOUT_GSUB_TABLE_HH */diff --git a/thirdparty/harfbuzz/src/hb-ot-layout-gsubgpos.hh b/thirdparty/harfbuzz/src/hb-ot-layout-gsubgpos.hhindex df029ae79cc..95091619014 100644--- a/thirdparty/harfbuzz/src/hb-ot-layout-gsubgpos.hh+++ b/thirdparty/harfbuzz/src/hb-ot-layout-gsubgpos.hh@@ -36,6 +36,7 @@#include "hb-ot-map.hh"#include "hb-ot-layout-common.hh"#include "hb-ot-layout-gdef-table.hh"+#include "hb-depend-data.hh"namespace OT {@@ -105,9 +106,12 @@ struct hb_closure_context_t :return true;/* Have we visited this lookup with the current set of glyphs? */- if (done_lookups_glyph_count->get (lookup_index) != glyphs->get_population ())+ unsigned pop = glyphs->get_population ();+ if (unlikely (pop == HB_MAP_VALUE_INVALID)) // Avoid sentinel interference.+ pop--;+ if (done_lookups_glyph_count->get (lookup_index) != pop){- done_lookups_glyph_count->set (lookup_index, glyphs->get_population ());+ done_lookups_glyph_count->set (lookup_index, pop);if (!done_lookups_glyph_set->has (lookup_index)){@@ -375,7 +379,417 @@ struct hb_collect_glyphs_context_t :void set_recurse_func (recurse_func_t func) { recurse_func = func; }};+struct hb_depend_context_t :+ hb_dispatch_context_t<hb_depend_context_t>+{+ enum glyph_set_type_t+ {+ GLYPH_SET_CLASS,+ GLYPH_SET_COVERAGE,+ GLYPH_SET_SINGLE+ };++ static constexpr hb_codepoint_t SINGLE_GLYPH_ACTIVE_FLAG = 0x80000000u;++ struct glyph_set_cache_key_t+ {+ glyph_set_cache_key_t () = default;+ glyph_set_cache_key_t (const void *data_, unsigned value_, glyph_set_type_t type_)+ : data (data_), value (value_), type (type_) {}++ bool operator == (const glyph_set_cache_key_t &o) const+ { return data == o.data && value == o.value && type == o.type; }++ uint32_t hash () const+ {+ uint32_t current = hb_hash ((uintptr_t) data);+ current = current * 31 + hb_hash (value);+ return current * 31 + hb_hash ((unsigned) type);+ }++ const void *data = nullptr;+ unsigned value = 0;+ glyph_set_type_t type = GLYPH_SET_CLASS;+ };++ struct context_set_cache_key_t+ {+ context_set_cache_key_t () = default;+ context_set_cache_key_t (const void *rule_,+ const void *record_,+ const void *data_,+ hb_codepoint_t active_glyphs_,+ unsigned value_,+ unsigned format_)+ : rule (rule_), record (record_), data (data_), active_glyphs (active_glyphs_),+ value (value_), format (format_) {}++ bool operator == (const context_set_cache_key_t &o) const+ {+ return rule == o.rule &&+ record == o.record &&+ data == o.data &&+ active_glyphs == o.active_glyphs &&+ value == o.value &&+ format == o.format;+ }++ uint32_t hash () const+ {+ uint32_t current = hb_hash ((uintptr_t) rule);+ current = current * 31 + hb_hash ((uintptr_t) record);+ current = current * 31 + hb_hash ((uintptr_t) data);+ current = current * 31 + hb_hash (active_glyphs);+ current = current * 31 + hb_hash (value);+ return current * 31 + hb_hash (format);+ }++ const void *rule = nullptr;+ const void *record = nullptr;+ const void *data = nullptr;+ hb_codepoint_t active_glyphs = HB_CODEPOINT_INVALID;+ unsigned value = 0;+ unsigned format = 0;+ };++ struct recurse_key_t+ {+ recurse_key_t () = default;+ recurse_key_t (unsigned lookup_index_,+ hb_codepoint_t active_glyphs_,+ hb_codepoint_t recurse_path_,+ hb_codepoint_t context_set_)+ : lookup_index (lookup_index_),+ active_glyphs (active_glyphs_),+ recurse_path (recurse_path_),+ context_set (context_set_) {}++ bool operator == (const recurse_key_t &o) const+ {+ return lookup_index == o.lookup_index &&+ active_glyphs == o.active_glyphs &&+ recurse_path == o.recurse_path &&+ context_set == o.context_set;+ }++ uint32_t hash () const+ {+ uint32_t current = 0x84222325;+ current = (current ^ hb_hash (lookup_index)) * 16777619;+ current = (current ^ hb_hash (active_glyphs)) * 16777619;+ current = (current ^ hb_hash (recurse_path)) * 16777619;+ current = (current ^ hb_hash (context_set)) * 16777619;+ return current;+ }++ unsigned lookup_index = 0;+ hb_codepoint_t active_glyphs = 0;+ hb_codepoint_t recurse_path = 0;+ hb_codepoint_t context_set = HB_CODEPOINT_INVALID;+ };++ typedef return_t (*recurse_func_t) (hb_depend_context_t *c, unsigned lookup_index, hb_bit_page_t *covered_seq_indices, unsigned seq_index, unsigned end_index);+ /* return_t is hb_empty_t — dispatch is purely for side-effects, like hb_closure_context_t. */+ template <typename T>+ return_t dispatch (const T &obj) { obj.depend (this); return hb_empty_t (); }+ static return_t default_return_value () { return hb_empty_t (); }++ void recurse (unsigned lookup_idx, hb_bit_page_t *covered_seq_indices, unsigned seq_index, unsigned end_index)+ {+ /* Cycle detection using call-stack semantics: block re-entry of a+ * lookup that is currently on the execution stack, but allow it again+ * once it has returned.+ *+ * A flat "visited" set would be wrong: the same lookup legitimately+ * appears more than once when a rule iterates over multiple sequence+ * positions — each such call is independent and must be processed.+ *+ * Cutting an in-progress cycle is safe because the active glyph set+ * can only stay the same or shrink as we recurse. If we re-encounter+ * lookup L while it is still on the stack, L is already executing+ * with a context at least as broad, so any edges a re-entry would add+ * are a subset of what L is already in the process of registering.+ *+ * lookups_seen is pre-seeded with the top-level lookup index in+ * GSUB_accelerator_t::depend before the direct depend() call, so+ * that indirect cycles of the form A→B→A are also caught here. */+ if (lookups_seen.has (lookup_idx)) return;+ lookups_seen.add (lookup_idx);++ /* Intern the ordered recursion path instead of copying and interning the+ * lookups_seen set. Path identity is more specific than set identity but+ * never merges states with different cycle-detection behavior. */+ hb_codepoint_t parent_path = recurse_path;+ uint64_t path_key = (uint64_t) parent_path << 32 | lookup_idx;+ hb_codepoint_t *path = nullptr;+ hb_codepoint_t path_index;+ if (!recurse_path_to_index.has (path_key, &path))+ {+ path_index = recurse_path_to_index.get_population () + 1;+ if (unlikely (!recurse_path_to_index.set (path_key, path_index)))+ {+ depend_data->fail ();+ lookups_seen.del (lookup_idx);+ return;+ }+ }+ else+ path_index = *path;+ recurse_path = path_index;+ recurse_func (this, lookup_idx, covered_seq_indices, seq_index, end_index);+ recurse_path = parent_path;+ lookups_seen.del (lookup_idx);+ }++ struct active_glyphs_frame_t+ {+ hb_set_t glyphs;+ hb_codepoint_t active_idx = HB_CODEPOINT_INVALID;+ bool use_root = false;+ };++ const hb_set_t& parent_active_glyphs ()+ {+ if (!active_glyphs_stack_depth)+ return *glyphs;++ const active_glyphs_frame_t &frame = active_glyphs_stack[active_glyphs_stack_depth - 1];+ return frame.use_root ? *glyphs : frame.glyphs;+ }++ hb_set_t* push_cur_active_glyphs (hb_codepoint_t active_idx = HB_CODEPOINT_INVALID)+ {+ if (active_glyphs_stack_depth == active_glyphs_stack.length &&+ unlikely (!active_glyphs_stack.push_or_fail ()))+ return nullptr;++ active_glyphs_frame_t &frame = active_glyphs_stack[active_glyphs_stack_depth++];+ frame.glyphs.clear ();+ frame.active_idx = active_idx;+ frame.use_root = false;+ return &frame.glyphs;+ }++ bool push_root_active_glyphs ()+ {+ if (active_glyphs_stack_depth == active_glyphs_stack.length &&+ unlikely (!active_glyphs_stack.push_or_fail ()))+ return false;++ active_glyphs_stack[active_glyphs_stack_depth++].use_root = true;+ return true;+ }++ bool pop_cur_done_glyphs ()+ {+ if (!active_glyphs_stack_depth)+ return false;++ active_glyphs_stack_depth--;+ return true;+ }++ bool get_parent_active_glyphs_index (hb_codepoint_t *active_idx)+ {+ if (!active_glyphs_stack_depth ||+ active_glyphs_stack[active_glyphs_stack_depth - 1].use_root)+ {+ *active_idx = HB_CODEPOINT_INVALID;+ return true;+ }++ active_glyphs_frame_t &frame = active_glyphs_stack[active_glyphs_stack_depth - 1];+ *active_idx = frame.active_idx;+ if (*active_idx != HB_CODEPOINT_INVALID)+ return true;++ hb_codepoint_t glyph;+ if (frame.glyphs.get_singleton (&glyph) &&+ likely (glyph < SINGLE_GLYPH_ACTIVE_FLAG))+ *active_idx = glyph | SINGLE_GLYPH_ACTIVE_FLAG;+ else if (!find_or_create_recurse_set (frame.glyphs, active_idx))+ return false;++ frame.active_idx = *active_idx;+ return true;+ }++ bool get_context_set_cache_key (const void *rule,+ const void *record,+ const void *data,+ unsigned value,+ unsigned format,+ context_set_cache_key_t *key)+ {+ hb_codepoint_t active_idx;+ if (!get_parent_active_glyphs_index (&active_idx))+ return false;+ *key = context_set_cache_key_t (rule, record, data, active_idx, value, format);+ return true;+ }++ bool get_recurse_key (unsigned lookup_idx, recurse_key_t *key)+ {+ /* The active glyphs and in-progress lookup set are part of the state.+ * Omitting the latter would make memoization incorrect for cyclic lookup+ * graphs whose available recursive paths depend on their ancestry.+ * Edge flags are not part of the state: they affect neither traversal nor+ * edge identity, so revisiting with different flags can only find edges+ * that the deduplication table already contains. */+ hb_codepoint_t active_idx;+ if (!get_parent_active_glyphs_index (&active_idx))+ return false;++ *key = recurse_key_t (lookup_idx,+ active_idx,+ recurse_path,+ depend_data->current_context_set_index);+ return !completed_recursions.has (*key);+ }++ void finish_recurse (const recurse_key_t &key)+ { depend_data->check_success (completed_recursions.set (key, true)); }++ void reset_recurse_cache ()+ {+ completed_recursions.clear ();+ recurse_path_to_index.clear ();+ recurse_path = 0;+ }++ bool find_or_create_recurse_set (const hb_set_t &set, hb_codepoint_t *index)+ {+ hb_codepoint_t *existing = nullptr;+ if (recurse_set_to_index.has (&set, &existing))+ {+ *index = *existing;+ return true;+ }++ hb_set_t *copy = hb_object_create<hb_set_t> ();+ if (unlikely (!copy))+ return depend_data->fail ();+ copy->set (set);+ if (unlikely (copy->in_error ()))+ {+ hb_set_destroy (copy);+ return depend_data->fail ();+ }++ *index = recurse_sets.length;+ if (unlikely (*index & SINGLE_GLYPH_ACTIVE_FLAG))+ {+ hb_set_destroy (copy);+ return depend_data->fail ();+ }+ if (unlikely (!recurse_sets.push_or_fail (hb::unique_ptr<hb_set_t> {copy})))+ return depend_data->fail ();+ if (unlikely (!recurse_set_to_index.set (recurse_sets[*index].get (), *index)))+ return depend_data->fail ();+ return true;+ }++ const hb_set_t *find_or_create_glyph_set (const void *data,+ unsigned value,+ glyph_set_type_t type);+ hb_codepoint_t find_or_create_cached_context_set (const hb_set_t *set);++ struct depend_scratch_t+ {+ void clear ()+ {+ preliminary_context.clear ();+ position_scratch.clear ();+ pos_glyphs.clear ();+ position_context.clear ();+ disjunctive_indices.clear ();+ filtered_disjunctive_indices.clear ();+ backtrack_sets.clear ();+ lookahead_sets.clear ();+ input_position_glyphs.clear ();+ cached_context_sets.clear ();+ compact_workspace.clear ();+ }+ hb_set_t preliminary_context;+ hb_set_t position_scratch;+ hb_set_t pos_glyphs;+ hb_set_t position_context;+ hb_set_t disjunctive_indices;+ hb_set_t filtered_disjunctive_indices;+ hb_vector_t<const hb_set_t *> backtrack_sets;+ hb_vector_t<const hb_set_t *> lookahead_sets;+ hb_vector_t<const hb_set_t *> input_position_glyphs;+ hb_vector_t<hb_codepoint_t> cached_context_sets;+ hb_vector_t<unsigned> compact_workspace;+ depend_scratch_t *next = nullptr;+ };++ depend_scratch_t *acquire_depend_scratch ()+ {+ depend_scratch_t *scratch = depend_scratch_pool;+ if (scratch)+ depend_scratch_pool = scratch->next;+ else+ {+ scratch = (depend_scratch_t *) hb_malloc (sizeof (depend_scratch_t));+ if (unlikely (!scratch))+ {+ depend_data->fail ();+ return nullptr;+ }+ new (scratch) depend_scratch_t ();+ }++ scratch->next = nullptr;+ scratch->clear ();+ return scratch;+ }++ void release_depend_scratch (depend_scratch_t *scratch)+ {+ scratch->next = depend_scratch_pool;+ depend_scratch_pool = scratch;+ }++ hb_depend_data_builder_t *depend_data;+ hb_face_t *face;+ hb_set_t *glyphs;+ hb_vector_t<active_glyphs_frame_t> active_glyphs_stack;+ unsigned active_glyphs_stack_depth = 0;+ recurse_func_t recurse_func;+ hb_codepoint_t lookup_index = HB_CODEPOINT_INVALID;+ hb_bit_set_t lookups_seen;+ hb_vector_t<hb::unique_ptr<hb_set_t>> recurse_sets;+ hb_hashmap_t<const hb_set_t *, hb_codepoint_t> recurse_set_to_index;+ hb_hashmap_t<uint64_t, hb_codepoint_t> recurse_path_to_index;+ hb_codepoint_t recurse_path = 0;+ hb_hashmap_t<recurse_key_t, bool> completed_recursions;+ hb_vector_t<hb::unique_ptr<hb_set_t>> glyph_sets;+ hb_hashmap_t<glyph_set_cache_key_t, hb_codepoint_t> glyph_set_to_index;+ hb_hashmap_t<uintptr_t, hb_codepoint_t> cached_context_set_indices;+ hb_hashmap_t<context_set_cache_key_t, hb_codepoint_t> context_set_cache;+ depend_scratch_t *depend_scratch_pool = nullptr;++ hb_depend_context_t (hb_depend_data_builder_t *depend_data_,+ hb_face_t *face_,+ hb_set_t *glyphs_)+ : depend_data (depend_data_),+ face(face_),+ glyphs (glyphs_),+ recurse_func (nullptr) {}+ ~hb_depend_context_t ()+ {+ while (depend_scratch_pool)+ {+ depend_scratch_t *scratch = depend_scratch_pool;+ depend_scratch_pool = scratch->next;+ scratch->~depend_scratch_t ();+ hb_free (scratch);+ }+ }+ void set_recurse_func (recurse_func_t func) { recurse_func = func; }+};template <typename set_t>struct hb_collect_coverage_context_t :@@ -577,9 +991,6 @@ struct skipping_iterator_treturn SKIP;}-#ifndef HB_OPTIMIZE_SIZE- HB_ALWAYS_INLINE-#endifbool next (unsigned *unsafe_to = nullptr){auto *info = c->buffer->info;@@ -608,9 +1019,6 @@ struct skipping_iterator_t*unsafe_to = end;return false;}-#ifndef HB_OPTIMIZE_SIZE- HB_ALWAYS_INLINE-#endifbool prev (unsigned *unsafe_from = nullptr){auto *out_info = c->buffer->out_info;@@ -851,7 +1259,10 @@ struct hb_ot_apply_context_t :* match_props has the set index.*/if (match_props & LookupFlag::UseMarkFilteringSet)- return gdef_accel.mark_set_covers (match_props >> 16, info->codepoint);+ {+ unsigned set_index = match_props >> 16;+ return gdef_accel.mark_set_covers (set_index, info->codepoint);+ }/* The second byte of match_props has the meaning* "ignore marks of attachment type different than@@ -1042,6 +1453,10 @@ struct hb_accelerate_subtables_context_t :{return digest.may_have (c->buffer->cur().codepoint) && apply_func (obj, c, nullptr);}+ bool apply_no_digest (hb_ot_apply_context_t *c) const+ {+ return apply_func (obj, c, nullptr);+ }#elsebool apply (hb_ot_apply_context_t *c) const{@@ -1051,6 +1466,14 @@ struct hb_accelerate_subtables_context_t :{return digest.may_have (c->buffer->cur().codepoint) && apply_cached_func (obj, c, external_cache);}+ bool apply_no_digest (hb_ot_apply_context_t *c) const+ {+ return apply_func (obj, c, external_cache);+ }+ bool apply_cached_no_digest (hb_ot_apply_context_t *c) const+ {+ return apply_cached_func (obj, c, external_cache);+ }bool cache_enter (hb_ot_apply_context_t *c) const{@@ -1256,6 +1679,69 @@ static inline void collect_coverage (hb_set_t *glyphs, unsigned value, const voicoverage = value;(data+coverage).collect_coverage (glyphs);}++inline const hb_set_t *+hb_depend_context_t::find_or_create_glyph_set (const void *data,+ unsigned value,+ glyph_set_type_t type)+{+ /* Class definitions and coverages are immutable for the lifetime of the+ * context, so their expanded glyph sets can be shared across traversals. */+ glyph_set_cache_key_t key (data, value, type);+ hb_codepoint_t *existing = nullptr;+ if (glyph_set_to_index.has (key, &existing))+ return glyph_sets[*existing].get ();++ hb_set_t *set = hb_object_create<hb_set_t> ();+ if (unlikely (!set))+ {+ depend_data->fail ();+ return nullptr;+ }++ if (type == GLYPH_SET_COVERAGE)+ collect_coverage (set, value, data);+ else if (type == GLYPH_SET_CLASS)+ collect_class (set, value, data);+ else+ set->add (value);+ if (unlikely (set->in_error ()))+ {+ hb_set_destroy (set);+ depend_data->fail ();+ return nullptr;+ }++ hb_codepoint_t index = glyph_sets.length;+ if (unlikely (!glyph_sets.push_or_fail (hb::unique_ptr<hb_set_t> {set})))+ {+ depend_data->fail ();+ return nullptr;+ }+ if (unlikely (!glyph_set_to_index.set (key, index)))+ {+ depend_data->fail ();+ return nullptr;+ }+ return glyph_sets[index].get ();+}++inline hb_codepoint_t+hb_depend_context_t::find_or_create_cached_context_set (const hb_set_t *set)+{+ uintptr_t key = (uintptr_t) set;+ hb_codepoint_t *existing = nullptr;+ if (cached_context_set_indices.has (key, &existing))+ return *existing;++ hb_codepoint_t index = depend_data->find_or_create_context_set (*set);+ if (unlikely (index == HB_CODEPOINT_INVALID))+ return HB_CODEPOINT_INVALID;+ if (unlikely (!cached_context_set_indices.set (key, index)))+ return depend_data->fail_invalid ();+ return index;+}+template <typename HBUINT>static inline void collect_array (hb_collect_glyphs_context_t *c HB_UNUSED,hb_set_t *glyphs,@@ -1484,7 +1970,7 @@ static bool match_input (hb_ot_apply_context_t *c,return_trace (false);}- total_component_count += _hb_glyph_info_get_lig_num_comps (&buffer->info[skippy_iter.idx]);+ total_component_count += _hb_glyph_info_get_lig_num_comps_in_ligation (&buffer->info[skippy_iter.idx]);}*end_position = skippy_iter.idx + 1;@@ -1588,7 +2074,7 @@ static inline bool ligate_input (hb_ot_apply_context_t *c,}last_lig_id = _hb_glyph_info_get_lig_id (&buffer->cur());- last_num_components = _hb_glyph_info_get_lig_num_comps (&buffer->cur());+ last_num_components = _hb_glyph_info_get_lig_num_comps_in_ligation (&buffer->cur());components_so_far += last_num_components;/* Skip the base glyph */@@ -1740,6 +2226,45 @@ static unsigned serialize_lookuprecord_array (hb_serialize_context_t *c,enum ContextFormat { SimpleContext = 1, ClassBasedContext = 2, CoverageBasedContext = 3 };+static inline const hb_set_t *+depend_position_glyphs (hb_depend_context_t *c,+ ContextFormat context_format,+ const void *data,+ unsigned value,+ bool filter_class_by_parent,+ hb_set_t *scratch,+ hb_vector_t<unsigned> *compact_workspace = nullptr)+{+ switch (context_format)+ {+ case ContextFormat::SimpleContext:+ return c->find_or_create_glyph_set (nullptr, value,+ hb_depend_context_t::GLYPH_SET_SINGLE);+ case ContextFormat::ClassBasedContext:+ {+ const hb_set_t *class_set = c->find_or_create_glyph_set (+ data, value, hb_depend_context_t::GLYPH_SET_CLASS);+ if (unlikely (!class_set))+ return nullptr;+ if (!filter_class_by_parent)+ return class_set;+ scratch->set (*class_set);+ scratch->intersect (c->parent_active_glyphs (), compact_workspace);+ break;+ }+ case ContextFormat::CoverageBasedContext:+ return c->find_or_create_glyph_set (+ data, value, hb_depend_context_t::GLYPH_SET_COVERAGE);+ }++ if (unlikely (scratch->in_error ()))+ {+ c->depend_data->fail ();+ return nullptr;+ }+ return scratch;+}+template <typename HBUINT>static void context_closure_recurse_lookups (hb_closure_context_t *c,unsigned inputCount, const HBUINT input[],@@ -1798,17 +2323,306 @@ static void context_closure_recurse_lookups (hb_closure_context_t *c,return;if (has_pos_glyphs) {*cur_active_glyphs = std::move (pos_glyphs);- } else {- *cur_active_glyphs = *c->glyphs;+ } else {+ *cur_active_glyphs = *c->glyphs;+ }++ unsigned endIndex = inputCount;+ if (context_format == ContextFormat::CoverageBasedContext)+ endIndex += 1;++ c->recurse (lookupRecord[i].lookupListIndex, &covered_seq_indicies, seqIndex, endIndex);++ c->pop_cur_done_glyphs ();+ }+}++static bool+context_depend_sets_are_cached (hb_depend_context_t *c,+ unsigned input_count,+ unsigned lookup_count,+ const LookupRecord lookup_records[],+ const void *rule,+ unsigned value,+ ContextFormat context_format,+ const void *data,+ hb_vector_t<hb_codepoint_t> *cached_context_sets)+{+ hb_codepoint_t active_idx = HB_CODEPOINT_INVALID;+ bool have_active_idx = false;+ for (unsigned i = 0; i < lookup_count; i++)+ {+ if (lookup_records[i].sequenceIndex >= input_count)+ continue;++ if (!have_active_idx)+ {+ if (unlikely (!c->get_parent_active_glyphs_index (&active_idx)))+ return false;+ have_active_idx = true;+ }++ hb_depend_context_t::context_set_cache_key_t key (+ rule, &lookup_records[i], data, active_idx, value, context_format);+ hb_codepoint_t *cached_context_set = nullptr;+ if (!c->context_set_cache.has (key, &cached_context_set))+ return false;+ if (unlikely (!cached_context_sets->push_or_fail (*cached_context_set)))+ return c->depend_data->fail ();+ }+ /* A rule with no valid records has no cache entries, and its preparation+ * can still allocate dependency sets in an observable order. */+ return have_active_idx;+}++template <typename HBUINT>+static void context_depend_recurse_lookups (hb_depend_context_t *c,+ unsigned inputCount, const HBUINT input[],+ unsigned lookupCount,+ const LookupRecord lookupRecord[] /* Array of LookupRecords--in design order */,+ const void *rule,+ unsigned value,+ ContextFormat context_format,+ const void *data,+ intersected_glyphs_func_t intersected_glyphs_func,+ void *cache,+ const hb_set_t &preliminary_context,+ const hb_vector_t<const hb_set_t *> *input_position_glyphs,+ const hb_vector_t<hb_codepoint_t> *cached_context_sets,+ hb_depend_context_t::depend_scratch_t *scratch)+{+ /* For depend graph extraction, we filter active glyphs by InputCoverage constraints+ * (same as closure), but we do NOT do sequential accumulation of outputs.+ *+ * - Position filtering (InputCoverage): Required. The contextual rule can only match+ * glyphs in its InputCoverage. Edges for other glyphs are spurious.+ * - Sequential accumulation: Not done. We want ALL possible edges, so we don't+ * limit later lookups based on outputs from earlier lookups in the same rule. */++ /* Sequence positions are tracked in one allocation-free bit page below.+ * A rule longer than HB_MAX_CONTEXT_LENGTH never applies during shaping+ * (the apply path rejects it), so skip it here instead of running past+ * the fixed page in add_range(). */+ if (unlikely (inputCount > HB_MAX_CONTEXT_LENGTH))+ return;++ hb_bit_page_t covered_seq_indices;+ hb_set_t &pos_glyphs = scratch->pos_glyphs;+ hb_set_t &position_context = scratch->position_context;+ hb_set_t &disjunctive_indices = scratch->disjunctive_indices;+ hb_set_t &filtered_disjunctive_indices = scratch->filtered_disjunctive_indices;+ unsigned cached_context_index = 0;+ for (unsigned int i = 0; i < lookupCount; i++)+ {+ unsigned seqIndex = lookupRecord[i].sequenceIndex;+ if (seqIndex >= inputCount)+ continue;++ hb_depend_context_t::context_set_cache_key_t context_cache_key;+ if (unlikely (!c->get_context_set_cache_key (rule, &lookupRecord[i], data, value,+ context_format, &context_cache_key)))+ return;++ hb_codepoint_t context_set_idx;+ hb_codepoint_t *cached_context_set_idx;+ if (cached_context_sets)+ context_set_idx = (*cached_context_sets)[cached_context_index++];+ else if (c->context_set_cache.has (context_cache_key, &cached_context_set_idx))+ context_set_idx = *cached_context_set_idx;+ else+ {+ if (unlikely (!input_position_glyphs))+ {+ c->depend_data->fail ();+ return;+ }++ /* Build position-specific context_set for this lookup. */+ position_context.clear (); // Will hold direct glyphs+ disjunctive_indices.clear (); // Will hold encoded set references+ filtered_disjunctive_indices.clear ();++ /* Process preliminary_context in one pass. */+ hb_codepoint_t elem = HB_SET_VALUE_INVALID;+ while (preliminary_context.next (&elem)) {+ if (!(elem & HB_DEPEND_CONTEXT_SET_FLAG)) {+ /* Direct glyph */+ position_context.add (elem);+ } else {+ /* Encoded set reference - defer processing until we have all direct requirements */+ disjunctive_indices.add (elem);+ }+ }++ /* Add singleton glyphs from OTHER input positions. */+ for (unsigned j = 0; j < input_position_glyphs->length; j++) {+ if (j != seqIndex && (*input_position_glyphs)[j]->get_population () == 1) {+ position_context.add ((*input_position_glyphs)[j]->get_min ());+ }+ }++ /* Now position_context has all direct requirements.+ * Process deferred encoded sets and filter them. */+ elem = HB_SET_VALUE_INVALID;+ while (disjunctive_indices.next (&elem)) {+ hb_codepoint_t set_idx = elem & 0x7FFFFFFF;+ const hb_set_t *original_set = c->depend_data->get_set_from_index (set_idx);+ if (unlikely (!original_set)) continue;++ /* Dependency context sets are never inverted. */+ if (!original_set->intersects (position_context)) {+ /* No overlap with position_context - add full requirement */+ filtered_disjunctive_indices.add (elem);+ }+ /* Otherwise: position_context intersects with original_set.+ * Since disjunctive requirements need only ONE glyph from the set,+ * and position_context already has a glyph from this set, the+ * requirement is satisfied - no need to add anything. */+ }++ /* Process non-singleton input positions. */+ for (unsigned j = 0; j < input_position_glyphs->length; j++) {+ if (j != seqIndex && (*input_position_glyphs)[j]->get_population () > 1) {+ /* Input-position sets are also never inverted. */+ if (!(*input_position_glyphs)[j]->intersects (position_context)) {+ /* No overlap with position_context - add full requirement */+ bool cached_set = context_format == ContextFormat::CoverageBasedContext ||+ (context_format == ContextFormat::ClassBasedContext && j != 0);+ hb_codepoint_t idx = cached_set+ ? c->find_or_create_cached_context_set ((*input_position_glyphs)[j])+ : c->depend_data->find_or_create_context_set (*(*input_position_glyphs)[j]);+ if (unlikely (idx == HB_CODEPOINT_INVALID))+ return;+ filtered_disjunctive_indices.add (HB_DEPEND_CONTEXT_SET_FLAG | idx);+ }+ /* Otherwise: position_context intersects, requirement satisfied */+ }+ }++ /* Combine direct + disjunctive. */+ position_context.union_ (filtered_disjunctive_indices);+ if (unlikely (position_context.in_error () ||+ filtered_disjunctive_indices.in_error ()))+ {+ c->depend_data->fail ();+ return;+ }++ context_set_idx = position_context.is_empty ()+ ? HB_CODEPOINT_INVALID+ : c->depend_data->find_or_create_context_set (position_context);+ if (unlikely (!position_context.is_empty () &&+ context_set_idx == HB_CODEPOINT_INVALID))+ return;++ if (unlikely (!c->context_set_cache.set (context_cache_key, context_set_idx)))+ {+ c->depend_data->fail ();+ return;+ }+ }++ /* Save outer context to restore after this lookup. When a contextual lookup+ * calls another contextual lookup, we want each lookup in this rule to see+ * the same outer context, not context from a sibling lookup. */+ hb_codepoint_t saved_context_set_index = c->depend_data->current_context_set_index;+ hb_subset_depend_edge_flags_t saved_edge_flags = c->depend_data->current_edge_flags;++ /* Detect nested contextual: if we already have a context set, we're inside+ * an outer contextual rule that called this one. The outer context will be+ * lost, so edges created here may over-approximate. */+ bool nested_contextual = (saved_context_set_index != HB_CODEPOINT_INVALID);++ /* Set for this position's edges */+ c->depend_data->current_context_set_index = context_set_idx;++ /* Mark edges from multi-position rules (inputCount > 1) as potentially+ * over-approximate. Depend extraction records edges based on what glyphs+ * COULD be at each position per the static input coverage/class. But during+ * closure computation, lookups within the rule are applied sequentially:+ * lookups at earlier positions may transform later positions, and multiple+ * lookups at the same position may interact (one produces a glyph, another+ * immediately consumes it as an "intermediate"). So a glyph matching the+ * coverage might not persist at that position when closure traverses. */+ c->depend_data->current_edge_flags = HB_SUBSET_DEPEND_EDGE_FLAG_NONE;+ if (inputCount > 1) {+ c->depend_data->current_edge_flags |= HB_SUBSET_DEPEND_EDGE_FLAG_FROM_CONTEXT_POSITION;+ }+ if (nested_contextual) {+ c->depend_data->current_edge_flags |= HB_SUBSET_DEPEND_EDGE_FLAG_FROM_NESTED_CONTEXT;+ }++ bool has_pos_glyphs = false;++ if (!covered_seq_indices.has (seqIndex))+ {+ has_pos_glyphs = true;+ pos_glyphs.clear ();+ if (seqIndex == 0)+ {+ switch (context_format) {+ case ContextFormat::SimpleContext:+ pos_glyphs.add (value);+ break;+ case ContextFormat::ClassBasedContext:+ intersected_glyphs_func (&c->parent_active_glyphs (), data, value, &pos_glyphs, cache);+ break;+ case ContextFormat::CoverageBasedContext:+ pos_glyphs.set (c->parent_active_glyphs ());+ break;+ }+ }+ else+ {+ const void *input_data = input;+ unsigned input_value = seqIndex - 1;+ if (context_format != ContextFormat::SimpleContext)+ {+ input_data = data;+ input_value = input[seqIndex - 1];+ }++ intersected_glyphs_func (c->glyphs, input_data, input_value, &pos_glyphs, cache);+ }+ }++ covered_seq_indices.add (seqIndex);+ if (has_pos_glyphs)+ {+ hb_codepoint_t active_idx = HB_CODEPOINT_INVALID;+ if (context_format == ContextFormat::SimpleContext)+ {+ hb_codepoint_t glyph = seqIndex ? pos_glyphs.get_min () : value;+ if (likely (glyph < hb_depend_context_t::SINGLE_GLYPH_ACTIVE_FLAG))+ active_idx = glyph | hb_depend_context_t::SINGLE_GLYPH_ACTIVE_FLAG;+ }+ hb_set_t *cur_active_glyphs = c->push_cur_active_glyphs (active_idx);+ if (unlikely (!cur_active_glyphs))+ {+ c->depend_data->current_context_set_index = saved_context_set_index;+ c->depend_data->current_edge_flags = saved_edge_flags;+ return;+ }+ *cur_active_glyphs = std::move (pos_glyphs);+ }+ else if (unlikely (!c->push_root_active_glyphs ()))+ {+ c->depend_data->current_context_set_index = saved_context_set_index;+ c->depend_data->current_edge_flags = saved_edge_flags;+ return;}unsigned endIndex = inputCount;if (context_format == ContextFormat::CoverageBasedContext)endIndex += 1;- c->recurse (lookupRecord[i].lookupListIndex, &covered_seq_indicies, seqIndex, endIndex);-+ c->recurse (lookupRecord[i].lookupListIndex, &covered_seq_indices, seqIndex, endIndex);c->pop_cur_done_glyphs ();++ /* Restore outer context after this lookup, so subsequent lookups in this+ * rule see the original context rather than this lookup's context. */+ c->depend_data->current_context_set_index = saved_context_set_index;+ c->depend_data->current_edge_flags = saved_edge_flags;}}@@ -1978,6 +2792,8 @@ struct ContextClosureLookupContextvoid *intersected_glyphs_cache;};+typedef ContextClosureLookupContext ContextDependLookupContext;+struct ContextCollectGlyphsLookupContext{ContextCollectGlyphsFuncs funcs;@@ -2025,6 +2841,86 @@ static inline void context_closure_lookup (hb_closure_context_t *c,lookup_context.intersected_glyphs_cache);}+template <typename HBUINT>+static inline void context_depend_lookup (hb_depend_context_t *c,+ unsigned int inputCount, /* Including the first glyph (not matched) */+ const HBUINT input[], /* Array of input values--start with second glyph */+ unsigned int lookupCount,+ const LookupRecord lookupRecord[],+ const void *rule,+ unsigned value, /* Index of first glyph in Coverage or Class value in ClassDef table */+ ContextDependLookupContext &lookup_context)+{+ if (!context_intersects (c->glyphs,+ inputCount, input,+ lookup_context))+ return;++ hb_depend_context_t::depend_scratch_t *scratch = c->acquire_depend_scratch ();+ if (unlikely (!scratch))+ return;+ HB_SCOPE_GUARD (c->release_depend_scratch (scratch));++ bool context_sets_cached = context_depend_sets_are_cached (+ c, inputCount, lookupCount, lookupRecord, rule, value,+ lookup_context.context_format, lookup_context.intersects_data,+ &scratch->cached_context_sets);+ if (unlikely (!c->depend_data->successful))+ return;++ /* Build preliminary_context (empty for ContextSubst - no backtrack/lookahead) */+ hb_set_t &preliminary_context = scratch->preliminary_context;++ /* Build glyph sets for ALL input positions */+ hb_set_t &position_scratch = scratch->position_scratch;+ hb_vector_t<const hb_set_t *> &input_position_glyphs = scratch->input_position_glyphs;++ /* Cached labels no longer need the expanded input-position sets. */+ if (!context_sets_cached)+ {+ /* Position 0 (Coverage glyph) — must be in both the class AND the+ * coverage, so intersect with parent_active_glyphs (= coverage ∩ glyphs+ * set by the ContextFormat2/3 caller). */+ const hb_set_t *pos0_glyphs = depend_position_glyphs (+ c, lookup_context.context_format, lookup_context.intersects_data, value,+ true, &position_scratch, &scratch->compact_workspace);+ if (unlikely (!pos0_glyphs ||+ !input_position_glyphs.push_or_fail (pos0_glyphs)))+ {+ c->depend_data->fail ();+ return;+ }++ /* Positions 1+ (Input array) */+ for (unsigned i = 0; i + 1 < inputCount; i++)+ {+ const hb_set_t *pos_glyphs = depend_position_glyphs (+ c, lookup_context.context_format, lookup_context.intersects_data,+ input[i], false, &position_scratch);+ if (unlikely (!pos_glyphs ||+ !input_position_glyphs.push_or_fail (pos_glyphs)))+ {+ c->depend_data->fail ();+ return;+ }+ }+ }++ context_depend_recurse_lookups (c,+ inputCount, input,+ lookupCount, lookupRecord,+ rule,+ value,+ lookup_context.context_format,+ lookup_context.intersects_data,+ lookup_context.funcs.intersected_glyphs,+ lookup_context.intersected_glyphs_cache,+ preliminary_context,+ context_sets_cached ? nullptr : &input_position_glyphs,+ context_sets_cached ? &scratch->cached_context_sets : nullptr,+ scratch);+}+template <typename HBUINT>static inline void context_collect_glyphs_lookup (hb_collect_glyphs_context_t *c,unsigned int inputCount, /* Including the first glyph (not matched) */@@ -2124,6 +3020,17 @@ struct Rulelookup_context);}+ void depend (hb_depend_context_t *c, unsigned value, ContextDependLookupContext &lookup_context) const+ {+ const auto &lookupRecord = StructAfter<UnsizedArrayOf<LookupRecord>>+ (inputZ.as_array ((inputCount ? inputCount - 1 : 0)));+ context_depend_lookup (c,+ inputCount, inputZ.arrayZ,+ lookupCount, lookupRecord.arrayZ,+ this,+ value, lookup_context);+ }+void closure (hb_closure_context_t *c, unsigned value, ContextClosureLookupContext &lookup_context) const{if (unlikely (c->lookup_limit_exceeded ())) return;@@ -2257,6 +3164,14 @@ struct RuleSet;}+ void depend (hb_depend_context_t *c, unsigned value, ContextDependLookupContext &lookup_context) const+ {+ + hb_iter (rule)+ | hb_map (hb_add (this))+ | hb_apply ([&] (const Rule &_) { _.depend (c, value, lookup_context); })+ ;+ }+void closure (hb_closure_context_t *c, unsigned value,ContextClosureLookupContext &lookup_context) const{@@ -2497,6 +3412,31 @@ struct ContextFormat1_4bool may_have_non_1to1 () const{ return true; }+ void depend (hb_depend_context_t *c) const+ {+ hb_set_t* cur_active_glyphs = c->push_cur_active_glyphs ();+ if (unlikely (!cur_active_glyphs)) return;+ get_coverage ().intersect_set (*c->glyphs, *cur_active_glyphs);++ ContextDependLookupContext lookup_context = {+ {intersects_glyph, intersected_glyph},+ ContextFormat::SimpleContext,+ nullptr,+ nullptr, /* intersects_cache */+ nullptr /* intersected_glyphs_cache */+ };++ + hb_zip (this+coverage, hb_range ((unsigned) ruleSet.len))+ | hb_filter ([&] (hb_codepoint_t _) {+ return c->parent_active_glyphs ().has (_);+ }, hb_first)+ | hb_map ([&](const hb_pair_t<hb_codepoint_t, unsigned> _) { return hb_pair_t<unsigned, const RuleSet&> (_.first, this+ruleSet[_.second]); })+ | hb_apply ([&] (const hb_pair_t<unsigned, const RuleSet&>& _) { _.second.depend (c, _.first, lookup_context); })+ ;++ c->pop_cur_done_glyphs ();+ }+void closure (hb_closure_context_t *c) const{hb_set_t* cur_active_glyphs = c->push_cur_active_glyphs ();@@ -2665,6 +3605,41 @@ struct ContextFormat2_5bool may_have_non_1to1 () const{ return true; }+ void depend (hb_depend_context_t *c) const+ {+ if (!(this+coverage).intersects (c->glyphs))+ return;++ hb_set_t* cur_active_glyphs = c->push_cur_active_glyphs ();+ if (unlikely (!cur_active_glyphs)) return;+ get_coverage ().intersect_set (*c->glyphs, *cur_active_glyphs);++ const ClassDef &class_def = this+classDef;++ hb_map_t cache;+ intersected_class_cache_t intersected_cache;+ ContextDependLookupContext lookup_context = {+ {intersects_class, intersected_class_glyphs},+ ContextFormat::ClassBasedContext,+ &class_def,+ &cache,+ &intersected_cache+ };++ + hb_enumerate (ruleSet)+ | hb_filter ([&] (unsigned _)+ { return class_def.intersects_class (&c->parent_active_glyphs (), _); },+ hb_first)+ | hb_apply ([&] (const hb_pair_t<unsigned, const typename Types::template OffsetTo<RuleSet>&> _)+ {+ const RuleSet& rule_set = this+_.second;+ rule_set.depend (c, _.first, lookup_context);+ })+ ;++ c->pop_cur_done_glyphs ();+ }+void closure (hb_closure_context_t *c) const{if (!(this+coverage).intersects (c->glyphs))@@ -2905,6 +3880,32 @@ struct ContextFormat3bool may_have_non_1to1 () const{ return true; }+ void depend (hb_depend_context_t *c) const+ {+ if (!(this+coverageZ[0]).intersects (c->glyphs))+ return;++ hb_set_t* cur_active_glyphs = c->push_cur_active_glyphs ();+ if (unlikely (!cur_active_glyphs)) return;+ get_coverage ().intersect_set (*c->glyphs, *cur_active_glyphs);++ const LookupRecord *lookupRecord = &StructAfter<LookupRecord> (coverageZ.as_array (glyphCount));+ ContextDependLookupContext lookup_context = {+ {intersects_coverage, intersected_coverage_glyphs},+ ContextFormat::CoverageBasedContext,+ this,+ nullptr, /* intersects_cache */+ nullptr /* intersected_glyphs_cache */+ };+ context_depend_lookup (c,+ glyphCount, (const HBUINT16 *) (coverageZ.arrayZ + 1),+ lookupCount, lookupRecord,+ this,+ coverageZ[0], lookup_context);++ c->pop_cur_done_glyphs ();+ }+void closure (hb_closure_context_t *c) const{if (!(this+coverageZ[0]).intersects (c->glyphs))@@ -3084,6 +4085,8 @@ struct ChainContextClosureLookupContextvoid *intersected_glyphs_cache;};+typedef ChainContextClosureLookupContext ChainContextDependLookupContext;+struct ChainContextCollectGlyphsLookupContext{ContextCollectGlyphsFuncs funcs;@@ -3106,21 +4109,23 @@ static inline bool chain_context_intersects (const hb_set_t *glyphs,const HBUINT lookahead[],ChainContextClosureLookupContext &lookup_context){- return array_is_subset_of (glyphs,+ bool bt_ok = array_is_subset_of (glyphs,backtrackCount, backtrack,lookup_context.funcs.intersects,lookup_context.intersects_data[0],- lookup_context.intersects_cache[0])- && array_is_subset_of (glyphs,+ lookup_context.intersects_cache[0]);+ bool in_ok = array_is_subset_of (glyphs,inputCount ? inputCount - 1 : 0, input,lookup_context.funcs.intersects,lookup_context.intersects_data[1],- lookup_context.intersects_cache[1])- && array_is_subset_of (glyphs,+ lookup_context.intersects_cache[1]);+ bool la_ok = array_is_subset_of (glyphs,lookaheadCount, lookahead,lookup_context.funcs.intersects,lookup_context.intersects_data[2],lookup_context.intersects_cache[2]);++ return bt_ok && in_ok && la_ok;}template <typename HBUINT>@@ -3151,6 +4156,179 @@ static inline void chain_context_closure_lookup (hb_closure_context_t *c,lookup_context.intersected_glyphs_cache);}+template <typename HBUINT>+static inline void chain_context_depend_lookup (hb_depend_context_t *c,+ unsigned int backtrackCount,+ const HBUINT backtrack[],+ unsigned int inputCount, /* Including the first glyph (not matched) */+ const HBUINT input[], /* Array of input values--start with second glyph */+ unsigned int lookaheadCount,+ const HBUINT lookahead[],+ unsigned int lookupCount,+ const LookupRecord lookupRecord[],+ const void *rule,+ unsigned value,+ ChainContextDependLookupContext &lookup_context)+{+ if (!chain_context_intersects (c->glyphs,+ backtrackCount, backtrack,+ inputCount, input,+ lookaheadCount, lookahead,+ lookup_context))+ return;++ hb_depend_context_t::depend_scratch_t *scratch = c->acquire_depend_scratch ();+ if (unlikely (!scratch))+ return;+ HB_SCOPE_GUARD (c->release_depend_scratch (scratch));++ bool context_sets_cached = context_depend_sets_are_cached (+ c, inputCount, lookupCount, lookupRecord, rule, value,+ lookup_context.context_format, lookup_context.intersects_data[1],+ &scratch->cached_context_sets);+ if (unlikely (!c->depend_data->successful))+ return;+ if (context_sets_cached)+ {+ context_depend_recurse_lookups (c,+ inputCount, input,+ lookupCount, lookupRecord,+ rule,+ value,+ lookup_context.context_format,+ lookup_context.intersects_data[1],+ lookup_context.funcs.intersected_glyphs,+ lookup_context.intersected_glyphs_cache,+ scratch->preliminary_context,+ nullptr,+ &scratch->cached_context_sets,+ scratch);+ return;+ }++ /* Cache misses and rules without valid records still perform the original+ * dependency-set interning in its observable order. */+ hb_set_t &position_scratch = scratch->position_scratch;+ hb_vector_t<const hb_set_t *> &backtrack_sets = scratch->backtrack_sets;+ hb_vector_t<const hb_set_t *> &lookahead_sets = scratch->lookahead_sets;++ /* Extract backtrack glyphs */+ for (unsigned i = 0; i < backtrackCount; i++)+ {+ const hb_set_t *pos_glyphs = depend_position_glyphs (+ c, lookup_context.context_format, lookup_context.intersects_data[0],+ backtrack[i], false, &position_scratch);+ if (unlikely (!pos_glyphs))+ return;+ if (!pos_glyphs->is_empty ())+ {+ if (unlikely (!backtrack_sets.push_or_fail (pos_glyphs)))+ {+ c->depend_data->fail ();+ return;+ }+ }+ }++ /* Extract lookahead glyphs */+ for (unsigned i = 0; i < lookaheadCount; i++)+ {+ const hb_set_t *pos_glyphs = depend_position_glyphs (+ c, lookup_context.context_format, lookup_context.intersects_data[2],+ lookahead[i], false, &position_scratch);+ if (unlikely (!pos_glyphs))+ return;+ if (!pos_glyphs->is_empty ())+ {+ if (unlikely (!lookahead_sets.push_or_fail (pos_glyphs)))+ {+ c->depend_data->fail ();+ return;+ }+ }+ }++ /* Build preliminary_context with backtrack + lookahead encoded */+ hb_set_t &preliminary_context = scratch->preliminary_context;+ for (const hb_set_t *back_set : backtrack_sets)+ {+ if (back_set->get_population () == 1) {+ preliminary_context.add (back_set->get_min ()); // Direct glyph+ } else if (back_set->get_population () > 1) {+ hb_codepoint_t set_idx = lookup_context.context_format == ContextFormat::SimpleContext+ ? c->depend_data->find_or_create_context_set (*back_set)+ : c->find_or_create_cached_context_set (back_set);+ if (unlikely (set_idx == HB_CODEPOINT_INVALID))+ return;+ preliminary_context.add (HB_DEPEND_CONTEXT_SET_FLAG | set_idx); // Encoded set reference+ }+ }+ for (const hb_set_t *look_set : lookahead_sets)+ {+ if (look_set->get_population () == 1) {+ preliminary_context.add (look_set->get_min ()); // Direct glyph+ } else if (look_set->get_population () > 1) {+ hb_codepoint_t set_idx = lookup_context.context_format == ContextFormat::SimpleContext+ ? c->depend_data->find_or_create_context_set (*look_set)+ : c->find_or_create_cached_context_set (look_set);+ if (unlikely (set_idx == HB_CODEPOINT_INVALID))+ return;+ preliminary_context.add (HB_DEPEND_CONTEXT_SET_FLAG | set_idx); // Encoded set reference+ }+ }+ if (unlikely (preliminary_context.in_error ()))+ {+ c->depend_data->fail ();+ return;+ }++ /* Build glyph sets for ALL input positions */+ hb_vector_t<const hb_set_t *> &input_position_glyphs = scratch->input_position_glyphs;++ if (!context_sets_cached)+ {+ /* Position 0 (first input coverage/class/glyph) — must be in both the+ * class AND the coverage, so intersect with parent_active_glyphs. */+ const hb_set_t *pos0_glyphs = depend_position_glyphs (+ c, lookup_context.context_format, lookup_context.intersects_data[1], value,+ true, &position_scratch, &scratch->compact_workspace);+ if (unlikely (!pos0_glyphs ||+ !input_position_glyphs.push_or_fail (pos0_glyphs)))+ {+ c->depend_data->fail ();+ return;+ }++ /* Positions 1+ (Input array) */+ for (unsigned i = 0; i + 1 < inputCount; i++)+ {+ const hb_set_t *pos_glyphs = depend_position_glyphs (+ c, lookup_context.context_format, lookup_context.intersects_data[1],+ input[i], false, &position_scratch);+ if (unlikely (!pos_glyphs ||+ !input_position_glyphs.push_or_fail (pos_glyphs)))+ {+ c->depend_data->fail ();+ return;+ }+ }+ }++ context_depend_recurse_lookups (c,+ inputCount, input,+ lookupCount, lookupRecord,+ rule,+ value,+ lookup_context.context_format,+ lookup_context.intersects_data[1],+ lookup_context.funcs.intersected_glyphs,+ lookup_context.intersected_glyphs_cache,+ preliminary_context,+ context_sets_cached ? nullptr : &input_position_glyphs,+ context_sets_cached ? &scratch->cached_context_sets : nullptr,+ scratch);+}+template <typename HBUINT>static inline void chain_context_collect_glyphs_lookup (hb_collect_glyphs_context_t *c,unsigned int backtrackCount,@@ -3260,6 +4438,21 @@ struct ChainRulelookup_context);}+ void depend (hb_depend_context_t *c, unsigned value, ChainContextDependLookupContext &lookup_context) const+ {+ const auto &input = StructAfter<decltype (inputX)> (backtrack);+ const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);+ const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);+ chain_context_depend_lookup (c,+ backtrack.len, backtrack.arrayZ,+ input.lenP1, input.arrayZ,+ lookahead.len, lookahead.arrayZ,+ lookup.len, lookup.arrayZ,+ this,+ value,+ lookup_context);+ }+void closure (hb_closure_context_t *c, unsigned value,ChainContextClosureLookupContext &lookup_context) const{@@ -3454,6 +4647,13 @@ struct ChainRuleSet| hb_any;}+ void depend (hb_depend_context_t *c, unsigned value, ChainContextDependLookupContext &lookup_context) const+ {+ + hb_iter (rule)+ | hb_map (hb_add (this))+ | hb_apply ([&] (const ChainRule &_) { _.depend (c, value, lookup_context); })+ ;+ }void closure (hb_closure_context_t *c, unsigned value, ChainContextClosureLookupContext &lookup_context) const{if (unlikely (c->lookup_limit_exceeded ())) return;@@ -3716,6 +4916,31 @@ struct ChainContextFormat1_4bool may_have_non_1to1 () const{ return true; }+ void depend (hb_depend_context_t *c) const+ {+ hb_set_t* cur_active_glyphs = c->push_cur_active_glyphs ();+ if (unlikely (!cur_active_glyphs)) return;+ get_coverage ().intersect_set (*c->glyphs, *cur_active_glyphs);++ ChainContextDependLookupContext lookup_context = {+ {intersects_glyph, intersected_glyph},+ ContextFormat::SimpleContext,+ {nullptr, nullptr, nullptr},+ {nullptr, nullptr, nullptr}, /* intersects_cache */+ nullptr /* intersected_glyphs_cache */+ };++ + hb_zip (this+coverage, hb_range ((unsigned) ruleSet.len))+ | hb_filter ([&] (hb_codepoint_t _) {+ return c->parent_active_glyphs ().has (_);+ }, hb_first)+ | hb_map ([&](const hb_pair_t<hb_codepoint_t, unsigned> _) { return hb_pair_t<unsigned, const ChainRuleSet&> (_.first, this+ruleSet[_.second]); })+ | hb_apply ([&] (const hb_pair_t<unsigned, const ChainRuleSet&>& _) { _.second.depend (c, _.first, lookup_context); })+ ;++ c->pop_cur_done_glyphs ();+ }+void closure (hb_closure_context_t *c) const{hb_set_t* cur_active_glyphs = c->push_cur_active_glyphs ();@@ -3886,6 +5111,45 @@ struct ChainContextFormat2_5bool may_have_non_1to1 () const{ return true; }+ void depend (hb_depend_context_t *c) const+ {+ if (!(this+coverage).intersects (c->glyphs))+ return;++ hb_set_t* cur_active_glyphs = c->push_cur_active_glyphs ();+ if (unlikely (!cur_active_glyphs)) return;+ get_coverage ().intersect_set (*c->glyphs, *cur_active_glyphs);++ const ClassDef &backtrack_class_def = this+backtrackClassDef;+ const ClassDef &input_class_def = this+inputClassDef;+ const ClassDef &lookahead_class_def = this+lookaheadClassDef;++ hb_map_t caches[3] = {};+ intersected_class_cache_t intersected_cache;+ ChainContextDependLookupContext lookup_context = {+ {intersects_class, intersected_class_glyphs},+ ContextFormat::ClassBasedContext,+ {&backtrack_class_def,+ &input_class_def,+ &lookahead_class_def},+ {&caches[0], &caches[1], &caches[2]},+ &intersected_cache+ };++ + hb_enumerate (ruleSet)+ | hb_filter ([&] (unsigned _)+ { return input_class_def.intersects_class (&c->parent_active_glyphs (), _); },+ hb_first)+ | hb_apply ([&] (const hb_pair_t<unsigned, const typename Types::template OffsetTo<ChainRuleSet>&> _)+ {+ const ChainRuleSet& chainrule_set = this+_.second;+ chainrule_set.depend (c, _.first, lookup_context);+ })+ ;++ c->pop_cur_done_glyphs ();+ }+void closure (hb_closure_context_t *c) const{if (!(this+coverage).intersects (c->glyphs))@@ -4183,6 +5447,38 @@ struct ChainContextFormat3bool may_have_non_1to1 () const{ return true; }+ void depend (hb_depend_context_t *c) const+ {+ const auto &input = StructAfter<decltype (inputX)> (backtrack);++ if (!(this+input[0]).intersects (c->glyphs))+ return;++ hb_set_t* cur_active_glyphs = c->push_cur_active_glyphs ();+ if (unlikely (!cur_active_glyphs))+ return;+ get_coverage ().intersect_set (*c->glyphs, *cur_active_glyphs);++ const auto &lookahead = StructAfter<decltype (lookaheadX)> (input);+ const auto &lookup = StructAfter<decltype (lookupX)> (lookahead);+ ChainContextDependLookupContext lookup_context = {+ {intersects_coverage, intersected_coverage_glyphs},+ ContextFormat::CoverageBasedContext,+ {this, this, this},+ {nullptr, nullptr, nullptr}, /* intersects_cache */+ nullptr /* intersected_glyphs_cache */+ };+ chain_context_depend_lookup (c,+ backtrack.len, (const HBUINT16 *) backtrack.arrayZ,+ input.len, (const HBUINT16 *) input.arrayZ + 1,+ lookahead.len, (const HBUINT16 *) lookahead.arrayZ,+ lookup.len, lookup.arrayZ,+ this,+ input[0], lookup_context);++ c->pop_cur_done_glyphs ();+ }+void closure (hb_closure_context_t *c) const{const auto &input = StructAfter<decltype (inputX)> (backtrack);@@ -4541,6 +5837,12 @@ struct hb_ot_layout_lookup_accelerator_thb_accelerate_subtables_context_t c_accelerate_subtables (thiz->subtables);lookup.dispatch (&c_accelerate_subtables);+ /* Invalid subtables do not collect and leave zeroed tail entries+ * (see the calloc note above); trim them so the apply paths never+ * see a null apply func. */+ while (count && !thiz->subtables[count - 1].apply_func)+ count--;+thiz->digest.init ();for (auto& subtable : hb_iter (thiz->subtables, count))thiz->digest.union_ (subtable.digest);@@ -4575,6 +5877,19 @@ struct hb_ot_layout_lookup_accelerator_tbool apply (hb_ot_apply_context_t *c, bool use_cache) const{c->lookup_accel = this;+ if (count == 1)+ {+ /* The accelerator digest is the union of the subtable digests, so+ * for a single subtable it equals that subtable's digest, which the+ * caller has already tested; skip the redundant retest. Zeroed+ * invalid entries were trimmed at create time, so the subtable is+ * always valid here. */+#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHE+ if (use_cache)+ return subtables[0].apply_cached_no_digest (c);+#endif+ return subtables[0].apply_no_digest (c);+ }#ifndef HB_NO_OT_LAYOUT_LOOKUP_CACHEif (use_cache){diff --git a/thirdparty/harfbuzz/src/hb-ot-layout.cc b/thirdparty/harfbuzz/src/hb-ot-layout.ccindex c11d0e465ca..d1a4ee3e309 100644--- a/thirdparty/harfbuzz/src/hb-ot-layout.cc+++ b/thirdparty/harfbuzz/src/hb-ot-layout.cc@@ -345,7 +345,7 @@ hb_ot_layout_get_glyphs_in_class (hb_face_t *face,* @start_offset: offset of the first attachment point to retrieve* @point_count: (inout) (nullable): Input = the maximum number of attachment points to return;* Output = the actual number of attachment points returned (may be zero)- * @point_array: (out) (array length=point_count): The array of attachment points found for the query+ * @point_array: (out) (array length=point_count) (nullable): The array of attachment points found for the query** Fetches a list of all attachment points for the specified glyph in the GDEF* table of the face. The list returned will begin at the offset provided.@@ -375,7 +375,7 @@ hb_ot_layout_get_attach_points (hb_face_t *face,* @start_offset: offset of the first caret position to retrieve* @caret_count: (inout) (nullable): Input = the maximum number of caret positions to return;* Output = the actual number of caret positions returned (may be zero)- * @caret_array: (out) (array length=caret_count): The array of caret positions found for the query+ * @caret_array: (out) (array length=caret_count) (nullable): The array of caret positions found for the query** Fetches a list of the caret positions defined for a ligature glyph in the GDEF* table of the font. The list returned will begin at the offset provided.@@ -446,7 +446,7 @@ get_gsubgpos_table (hb_face_t *face,* @start_offset: offset of the first script tag to retrieve* @script_count: (inout) (nullable): Input = the maximum number of script tags to return;* Output = the actual number of script tags returned (may be zero)- * @script_tags: (out) (array length=script_count): The array of #hb_tag_t script tags found for the query+ * @script_tags: (out) (array length=script_count) (nullable): The array of #hb_tag_t script tags found for the query** Fetches a list of all scripts enumerated in the specified face's GSUB table* or GPOS table. The list returned will begin at the offset provided.@@ -615,7 +615,7 @@ hb_ot_layout_table_select_script (hb_face_t *face,* @start_offset: offset of the first feature tag to retrieve* @feature_count: (inout) (nullable): Input = the maximum number of feature tags to return;* Output = the actual number of feature tags returned (may be zero)- * @feature_tags: (out) (array length=feature_count): Array of feature tags found in the table+ * @feature_tags: (out) (array length=feature_count) (nullable): Array of feature tags found in the table** Fetches a list of all feature tags in the given face's GSUB or GPOS table.* Note that there might be duplicate feature tags, belonging to different@@ -685,7 +685,7 @@ hb_ot_layout_table_find_feature (hb_face_t *face,* @start_offset: offset of the first language tag to retrieve* @language_count: (inout) (nullable): Input = the maximum number of language tags to return;* Output = the actual number of language tags returned (may be zero)- * @language_tags: (out) (array length=language_count): Array of language tags found in the table+ * @language_tags: (out) (array length=language_count) (nullable): Array of language tags found in the table** Fetches a list of language tags in the given face's GSUB or GPOS table, underneath* the specified script index. The list returned will begin at the offset provided.@@ -913,7 +913,7 @@ hb_ot_layout_language_get_required_feature (hb_face_t *face,* @start_offset: offset of the first feature tag to retrieve* @feature_count: (inout) (nullable): Input = the maximum number of feature tags to return;* Output: the actual number of feature tags returned (may be zero)- * @feature_indexes: (out) (array length=feature_count): The array of feature indexes found for the query+ * @feature_indexes: (out) (array length=feature_count) (nullable): The array of feature indexes found for the query** Fetches a list of all features in the specified face's GSUB table* or GPOS table, underneath the specified script and language. The list@@ -949,7 +949,7 @@ hb_ot_layout_language_get_feature_indexes (hb_face_t *face,* @start_offset: offset of the first feature tag to retrieve* @feature_count: (inout) (nullable): Input = the maximum number of feature tags to return;* Output = the actual number of feature tags returned (may be zero)- * @feature_tags: (out) (array length=feature_count): The array of #hb_tag_t feature tags found for the query+ * @feature_tags: (out) (array length=feature_count) (nullable): The array of #hb_tag_t feature tags found for the query** Fetches a list of all features in the specified face's GSUB table* or GPOS table, underneath the specified script and language. The list@@ -975,7 +975,7 @@ hb_ot_layout_language_get_feature_tags (hb_face_t *face,static_assert ((sizeof (unsigned int) == sizeof (hb_tag_t)), "");unsigned int ret = l.get_feature_indexes (start_offset, feature_count, (unsigned int *) feature_tags);- if (feature_tags) {+ if (feature_count && feature_tags) {unsigned int count = *feature_count;for (unsigned int i = 0; i < count; i++)feature_tags[i] = g.get_feature_tag ((unsigned int) feature_tags[i]);@@ -1037,7 +1037,7 @@ hb_ot_layout_language_find_feature (hb_face_t *face,* @start_offset: offset of the first lookup to retrieve* @lookup_count: (inout) (nullable): Input = the maximum number of lookups to return;* Output = the actual number of lookups returned (may be zero)- * @lookup_indexes: (out) (array length=lookup_count): The array of lookup indexes found for the query+ * @lookup_indexes: (out) (array length=lookup_count) (nullable): The array of lookup indexes found for the query** Fetches a list of all lookups enumerated for the specified feature, in* the specified face's GSUB table or GPOS table. The list returned will@@ -1475,7 +1475,7 @@ hb_ot_layout_table_find_feature_variations (hb_face_t *face,* @start_offset: offset of the first lookup to retrieve* @lookup_count: (inout) (nullable): Input = the maximum number of lookups to return;* Output = the actual number of lookups returned (may be zero)- * @lookup_indexes: (out) (array length=lookup_count): The array of lookups found for the query+ * @lookup_indexes: (out) (array length=lookup_count) (nullable): The array of lookups found for the query** Fetches a list of all lookups enumerated for the specified feature, in* the specified face's GSUB table or GPOS table, enabled at the specified@@ -1854,7 +1854,7 @@ hb_ot_layout_feature_get_name_ids (hb_face_t *face,* @start_offset: offset of the first character to retrieve* @char_count: (inout) (nullable): Input = the maximum number of characters to return;* Output = the actual number of characters returned (may be zero)- * @characters: (out caller-allocates) (array length=char_count): A buffer pointer.+ * @characters: (out caller-allocates) (array length=char_count) (nullable): A buffer pointer.* The Unicode codepoints of the characters for which this feature provides* glyph variants.*@@ -2288,7 +2288,7 @@ hb_ot_layout_get_horizontal_baseline_tag_for_script (hb_script_t script)* @language_tag: language tag, currently unused.* @coord: (out) (nullable): baseline value if found.*- * Fetches a baseline value from the face.+ * Fetches a baseline value from the font.** Return value: `true` if found baseline value in the font.*@@ -2314,7 +2314,7 @@ hb_ot_layout_get_baseline (hb_font_t *font,* @language: (nullable): language, currently unused.* @coord: (out) (nullable): baseline value if found.*- * Fetches a baseline value from the face.+ * Fetches a baseline value from the font.** This function is like hb_ot_layout_get_baseline() but takes* #hb_script_t and #hb_language_t instead of OpenType #hb_tag_t.@@ -2350,7 +2350,7 @@ hb_ot_layout_get_baseline2 (hb_font_t *font,* @language_tag: language tag, currently unused.* @coord: (out): baseline value if found.*- * Fetches a baseline value from the face, and synthesizes+ * Fetches a baseline value from the font, and synthesizes* it if the font does not have it.** Since: 4.0.0@@ -2389,7 +2389,7 @@ hb_ot_layout_get_baseline_with_fallback (hb_font_t *font,hb_font_get_nominal_glyph (font, '-', &glyph)) &&hb_font_get_glyph_extents (font, glyph, &extents)){- *coord = extents.y_bearing + extents.height / 2;+ *coord = hb_saturate_add (extents.y_bearing, extents.height / 2);}else{@@ -2421,9 +2421,11 @@ hb_ot_layout_get_baseline_with_fallback (hb_font_t *font,&embox_bottom);if (baseline_tag == HB_OT_LAYOUT_BASELINE_TAG_IDEO_FACE_TOP_OR_RIGHT)- *coord = embox_top + (embox_bottom - embox_top) / 10;+ *coord = hb_saturate_add (embox_top,+ hb_clamp_to<hb_position_t> (((int64_t) embox_bottom - embox_top) / 10));else- *coord = embox_bottom + (embox_top - embox_bottom) / 10;+ *coord = hb_saturate_add (embox_bottom,+ hb_clamp_to<hb_position_t> (((int64_t) embox_top - embox_bottom) / 10));}break;@@ -2434,7 +2436,8 @@ hb_ot_layout_get_baseline_with_fallback (hb_font_t *font,script_tag,language_tag,coord))- *coord += HB_DIRECTION_IS_HORIZONTAL (direction) ? font->y_scale : font->x_scale;+ *coord = hb_saturate_add (*coord,+ HB_DIRECTION_IS_HORIZONTAL (direction) ? font->y_scale : font->x_scale);else{hb_font_extents_t font_extents;@@ -2450,7 +2453,8 @@ hb_ot_layout_get_baseline_with_fallback (hb_font_t *font,script_tag,language_tag,coord))- *coord -= HB_DIRECTION_IS_HORIZONTAL (direction) ? font->y_scale : font->x_scale;+ *coord = hb_saturate_sub (*coord,+ HB_DIRECTION_IS_HORIZONTAL (direction) ? font->y_scale : font->x_scale);else{hb_font_extents_t font_extents;@@ -2510,10 +2514,10 @@ hb_ot_layout_get_baseline_with_fallback (hb_font_t *font,hb_font_get_glyph_extents (font, glyph, &extents))*coord = extents.y_bearing;else- *coord = font->y_scale * 6 / 10; // FIXME makes assumptions about origin+ *coord = hb_clamp_to<hb_position_t> ((int64_t) font->y_scale * 6 / 10); // FIXME makes assumptions about origin}else- *coord = font->x_scale * 6 / 10; // FIXME makes assumptions about origin+ *coord = hb_clamp_to<hb_position_t> ((int64_t) font->x_scale * 6 / 10); // FIXME makes assumptions about originbreak;case HB_OT_LAYOUT_BASELINE_TAG_IDEO_EMBOX_CENTRAL:@@ -2531,7 +2535,7 @@ hb_ot_layout_get_baseline_with_fallback (hb_font_t *font,script_tag,language_tag,&bottom);- *coord = (top + bottom) / 2;+ *coord = hb_clamp_to<hb_position_t> (((int64_t) top + bottom) / 2);}break;@@ -2551,7 +2555,7 @@ hb_ot_layout_get_baseline_with_fallback (hb_font_t *font,script_tag,language_tag,&bottom);- *coord = (top + bottom) / 2;+ *coord = hb_clamp_to<hb_position_t> (((int64_t) top + bottom) / 2);}break;@@ -2572,7 +2576,7 @@ hb_ot_layout_get_baseline_with_fallback (hb_font_t *font,* @language: (nullable): language, currently unused.* @coord: (out): baseline value if found.*- * Fetches a baseline value from the face, and synthesizes+ * Fetches a baseline value from the font, and synthesizes* it if the font does not have it.** This function is like hb_ot_layout_get_baseline_with_fallback() but takes@@ -2629,7 +2633,7 @@ struct hb_get_glyph_alternates_dispatch_t :* @start_offset: starting offset.* @alternate_count: (inout) (nullable): Input = the maximum number of alternate glyphs to return;* Output = the actual number of alternate glyphs returned (may be zero).- * @alternate_glyphs: (out caller-allocates) (array length=alternate_count): A glyphs buffer.+ * @alternate_glyphs: (out caller-allocates) (array length=alternate_count) (nullable): A glyphs buffer.* Alternate glyphs associated with the glyph id.** Fetches alternates of a glyph from a given GSUB lookup index. Note that for one-to-one GSUB@@ -2764,13 +2768,13 @@ hb_ot_layout_lookup_get_optical_bound (hb_font_t *font,ret = pos.x_offset;break;case HB_DIRECTION_RTL:- ret = pos.x_advance - pos.x_offset;+ ret = hb_saturate_sub (pos.x_advance, pos.x_offset);break;case HB_DIRECTION_TTB:ret = pos.y_offset;break;case HB_DIRECTION_BTT:- ret = pos.y_advance - pos.y_offset;+ ret = hb_saturate_sub (pos.y_advance, pos.y_offset);break;case HB_DIRECTION_INVALID:default:diff --git a/thirdparty/harfbuzz/src/hb-ot-layout.hh b/thirdparty/harfbuzz/src/hb-ot-layout.hhindex 945e735671f..e3eaf13cb8d 100644--- a/thirdparty/harfbuzz/src/hb-ot-layout.hh+++ b/thirdparty/harfbuzz/src/hb-ot-layout.hh@@ -159,7 +159,8 @@ static inline unsigned int_hb_next_syllable (hb_buffer_t *buffer, unsigned int start){hb_glyph_info_t *info = buffer->info;- unsigned int count = buffer->len;+ unsigned int count = start + hb_min (buffer->len - start,+ (unsigned) HB_MAX_SYLLABLE_LENGTH);unsigned int syllable = info[start].syllable();while (++start < count && syllable == info[start].syllable())@@ -567,6 +568,20 @@ _hb_glyph_info_multiplied (const hb_glyph_info_t *info)return info->glyph_props() & HB_OT_LAYOUT_GLYPH_PROPS_MULTIPLIED;}+static inline unsigned int+_hb_glyph_info_get_lig_num_comps_in_ligation (const hb_glyph_info_t *info)+{+ /* When a glyph is decomposed by a MultipleSubst and its pieces later become+ * components of a ligature, the pieces belong to the same ligature component+ * as the first piece, matching how MarkBasePos attaches marks only to the+ * first piece. So the non-first pieces contribute no extra component.+ * https://github.com/harfbuzz/harfbuzz/issues/4969 */+ if (_hb_glyph_info_multiplied (info) &&+ _hb_glyph_info_get_lig_comp (info))+ return 0;+ return _hb_glyph_info_get_lig_num_comps (info);+}+static inline bool_hb_glyph_info_ligated_and_didnt_multiply (const hb_glyph_info_t *info){diff --git a/thirdparty/harfbuzz/src/hb-ot-math-table.hh b/thirdparty/harfbuzz/src/hb-ot-math-table.hhindex f79808fa925..ccade564924 100644--- a/thirdparty/harfbuzz/src/hb-ot-math-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-math-table.hh@@ -30,6 +30,7 @@#include "hb-open-type.hh"#include "hb-ot-layout-common.hh"#include "hb-ot-math.h"+#include "hb-depend-data.hh"namespace OT {@@ -37,9 +38,9 @@ namespace OT {struct MathValueRecord{hb_position_t get_x_value (hb_font_t *font, const void *base) const- { return font->em_scale_x (value) + (base+deviceTable).get_x_delta (font); }+ { return hb_saturate_add (font->em_scale_x (value), (base+deviceTable).get_x_delta (font)); }hb_position_t get_y_value (hb_font_t *font, const void *base) const- { return font->em_scale_y (value) + (base+deviceTable).get_y_delta (font); }+ { return hb_saturate_add (font->em_scale_y (value), (base+deviceTable).get_y_delta (font)); }MathValueRecord* copy (hb_serialize_context_t *c, const void *base) const{@@ -355,7 +356,10 @@ struct MathKernunsigned int pos;auto cmp = +[](const void* key, const void* p,int sign, hb_font_t* font, const MathKern* mathKern) -> int {- return sign * *(hb_position_t*)key - sign * ((MathValueRecord*)p)->get_y_value(font, mathKern);+ hb_position_t a = *(hb_position_t *) key;+ hb_position_t b = ((MathValueRecord *) p)->get_y_value (font, mathKern);+ if (a == b) return 0;+ return sign > 0 ? (a < b ? -1 : +1) : (b < a ? -1 : +1);};unsigned int i = hb_bsearch_impl(&pos, correction_height, correctionHeight,heightCount, MathValueRecord::static_size,@@ -372,7 +376,7 @@ struct MathKernconst MathValueRecord* kernValue = mathValueRecordsZ.arrayZ + heightCount;const unsigned int entriesCount = heightCount + 1;- if (entries_count)+ if (entries_count && kern_entries){unsigned int start = hb_min (start_offset, entriesCount);unsigned int end = hb_min (start + *entries_count, entriesCount);@@ -662,6 +666,9 @@ struct MathGlyphVariantRecordreturn_trace (c->check_struct (this));}+ void depend (hb_depend_data_builder_t *depend_data, unsigned source) const+ { depend_data->add_depend(source, HB_OT_TAG_MATH, variantGlyph); }+void closure_glyphs (hb_set_t *variant_glyphs) const{ variant_glyphs->add (variantGlyph); }@@ -723,6 +730,9 @@ struct MathGlyphPartRecord(partFlags & PartFlags::Defined);}+ void depend (hb_depend_data_builder_t *depend_data, unsigned source) const+ { depend_data->add_depend(source, HB_OT_TAG_MATH, glyph); }+void closure_glyphs (hb_set_t *variant_glyphs) const{ variant_glyphs->add (glyph); }@@ -776,7 +786,7 @@ struct MathGlyphAssemblyhb_ot_math_glyph_part_t *parts /* OUT */,hb_position_t *italics_correction /* OUT */) const{- if (parts_count)+ if (parts_count && parts){int64_t mult = font->dir_mult (direction);for (auto _ : hb_zip (partRecords.as_array ().sub_array (start_offset, parts_count),@@ -790,6 +800,12 @@ struct MathGlyphAssemblyreturn partRecords.len;}+ void depend (hb_depend_data_builder_t *depend_data, unsigned source) const+ {+ for (const auto& _ : partRecords.iter ())+ _.depend (depend_data, source);+ }+void closure_glyphs (hb_set_t *variant_glyphs) const{for (const auto& _ : partRecords.iter ())@@ -845,7 +861,7 @@ struct MathGlyphConstructionunsigned int *variants_count, /* IN/OUT */hb_ot_math_glyph_variant_t *variants /* OUT */) const{- if (variants_count)+ if (variants_count && variants){int64_t mult = font->dir_mult (direction);for (auto _ : hb_zip (mathGlyphVariantRecord.as_array ().sub_array (start_offset, variants_count),@@ -855,6 +871,14 @@ struct MathGlyphConstructionreturn mathGlyphVariantRecord.len;}+ void depend (hb_depend_data_builder_t *depend_data, unsigned source) const+ {+ (this+glyphAssembly).depend (depend_data, source);++ for (const auto& _ : mathGlyphVariantRecord.iter ())+ _.depend (depend_data, source);+ }+void closure_glyphs (hb_set_t *variant_glyphs) const{(this+glyphAssembly).closure_glyphs (variant_glyphs);@@ -877,6 +901,34 @@ struct MathGlyphConstructionstruct MathVariants{+ void depend (hb_depend_data_builder_t *depend_data) const+ {+ const hb_array_t<const Offset16To<MathGlyphConstruction>> glyph_construction_offsets = glyphConstruction.as_array (vertGlyphCount + horizGlyphCount);++ if (vertGlyphCoverage)+ {+ const auto vert_offsets = glyph_construction_offsets.sub_array (0, vertGlyphCount);+ + hb_zip (this+vertGlyphCoverage, vert_offsets)+ | hb_apply ([&] (const hb_pair_t<hb_codepoint_t, const Offset16To<MathGlyphConstruction>&> &_)+ {+ const MathGlyphConstruction &mgc = this+_.second;+ mgc.depend (depend_data, _.first);+ })+ ;+ }+ if (horizGlyphCoverage)+ {+ const auto hori_offsets = glyph_construction_offsets.sub_array (vertGlyphCount, horizGlyphCount);+ + hb_zip (this+horizGlyphCoverage, hori_offsets)+ | hb_apply ([&] (const hb_pair_t<hb_codepoint_t, const Offset16To<MathGlyphConstruction>&> &_)+ {+ const MathGlyphConstruction &mgc = this+_.second;+ mgc.depend (depend_data, _.first);+ })+ ;+ }+ }+void closure_glyphs (const hb_set_t *glyph_set,hb_set_t *variant_glyphs) const{@@ -931,7 +983,7 @@ struct MathVariantsbool subset (hb_subset_context_t *c) const{TRACE_SUBSET (this);- const hb_set_t &glyphset = c->plan->_glyphset_mathed;+ const hb_set_t &glyphset = c->plan->_glyphset_cmaped;const hb_map_t &glyph_map = *c->plan->glyph_map;auto *out = c->serializer->start_embed (*this);@@ -1073,6 +1125,12 @@ struct MATHbool has_data () const { return version.to_int (); }+ void depend (hb_depend_data_builder_t *depend_data) const+ {+ if (mathVariants)+ (this+mathVariants).depend (depend_data);+ }+void closure_glyphs (hb_set_t *glyph_set) const{if (mathVariants)diff --git a/thirdparty/harfbuzz/src/hb-ot-math.cc b/thirdparty/harfbuzz/src/hb-ot-math.ccindex 719a802d5e5..91ef8a894b5 100644--- a/thirdparty/harfbuzz/src/hb-ot-math.cc+++ b/thirdparty/harfbuzz/src/hb-ot-math.cc@@ -206,7 +206,7 @@ hb_ot_math_get_glyph_kerning (hb_font_t *font,* @start_offset: offset of the first kern entry to retrieve* @entries_count: (inout) (optional): Input = the maximum number of kern entries to return;* Output = the actual number of kern entries returned- * @kern_entries: (out caller-allocates) (array length=entries_count): array of kern entries returned+ * @kern_entries: (out caller-allocates) (array length=entries_count) (nullable): array of kern entries returned** Fetches the raw MathKern (cut-in) data for the specified font, glyph index,* and @kern. The corresponding list of kern values and correction heights is@@ -251,7 +251,7 @@ hb_ot_math_get_glyph_kernings (hb_font_t *font,* @start_offset: offset of the first variant to retrieve* @variants_count: (inout): Input = the maximum number of variants to return;* Output = the actual number of variants returned- * @variants: (out) (array length=variants_count): array of variants returned+ * @variants: (out) (array length=variants_count) (nullable): array of variants returned** Fetches the MathGlyphConstruction for the specified font, glyph index, and* direction. The corresponding list of size variants is returned as a list of@@ -313,7 +313,7 @@ hb_ot_math_get_min_connector_overlap (hb_font_t *font,* @start_offset: offset of the first glyph part to retrieve* @parts_count: (inout): Input = maximum number of glyph parts to return;* Output = actual number of parts returned- * @parts: (out) (array length=parts_count): the glyph parts returned+ * @parts: (out) (array length=parts_count) (nullable): the glyph parts returned* @italics_correction: (out): italics correction of the glyph assembly** Fetches the GlyphAssembly for the specified font, glyph index, and direction.diff --git a/thirdparty/harfbuzz/src/hb-ot-meta-table.hh b/thirdparty/harfbuzz/src/hb-ot-meta-table.hhindex 658db584c7d..5365774de7d 100644--- a/thirdparty/harfbuzz/src/hb-ot-meta-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-meta-table.hh@@ -83,7 +83,7 @@ struct metaunsigned int *count,hb_ot_meta_tag_t *entries) const{- if (count)+ if (count && entries){+ table->dataMaps.as_array ().sub_array (start_offset, count)| hb_map (&DataMap::get_tag)diff --git a/thirdparty/harfbuzz/src/hb-ot-meta.cc b/thirdparty/harfbuzz/src/hb-ot-meta.ccindex 35c8eb523f9..99ada452b40 100644--- a/thirdparty/harfbuzz/src/hb-ot-meta.cc+++ b/thirdparty/harfbuzz/src/hb-ot-meta.cc@@ -42,7 +42,7 @@* @face: a face object* @start_offset: iteration's start offset* @entries_count:(inout) (optional): buffer size as input, filled size as output- * @entries: (out caller-allocates) (array length=entries_count): entries tags buffer+ * @entries: (out caller-allocates) (array length=entries_count) (nullable): entries tags buffer** Fetches all available feature types.*diff --git a/thirdparty/harfbuzz/src/hb-ot-metrics.cc b/thirdparty/harfbuzz/src/hb-ot-metrics.ccindex e314d946b62..26e3fdeb2d3 100644--- a/thirdparty/harfbuzz/src/hb-ot-metrics.cc+++ b/thirdparty/harfbuzz/src/hb-ot-metrics.cc@@ -178,7 +178,7 @@ hb_ot_metrics_get_position (hb_font_t *font,bool ret = GET_METRIC_Y (hhea, caretSlopeRise);if (position)- *position *= mult;+ *position = hb_clamp_to<hb_position_t> ((int64_t) *position * mult);return ret;}@@ -193,10 +193,11 @@ hb_ot_metrics_get_position (hb_font_t *font,if (position){- *position *= mult;+ *position = hb_clamp_to<hb_position_t> ((int64_t) *position * mult);if (font->slant)- *position += roundf (mult * font->slant_xy * rise);+ *position = hb_saturate_add (*position,+ hb_clamp_to<hb_position_t> (roundf (mult * font->slant_xy * rise)));}return ret;@@ -326,9 +327,10 @@ hb_ot_metrics_get_position_with_fallback (hb_font_t *font,case HB_OT_METRICS_TAG_CAP_HEIGHT:if (hb_font_get_nominal_glyph (font, 'O', &glyph) &&hb_font_get_glyph_extents (font, glyph, &extents))- *position = extents.height + 2 * extents.y_bearing;+ *position = hb_clamp_to<hb_position_t> ((int64_t) extents.height ++ 2 * (int64_t) extents.y_bearing);else- *position = font->y_scale * 2 / 3;+ *position = hb_clamp_to<hb_position_t> ((int64_t) font->y_scale * 2 / 3);break;case HB_OT_METRICS_TAG_STRIKEOUT_SIZE:@@ -347,17 +349,17 @@ hb_ot_metrics_get_position_with_fallback (hb_font_t *font,break;case HB_OT_METRICS_TAG_UNDERLINE_OFFSET:- *position = - font->y_scale / 18;+ *position = hb_saturate_neg (font->y_scale) / 18;break;case HB_OT_METRICS_TAG_SUBSCRIPT_EM_X_SIZE:case HB_OT_METRICS_TAG_SUPERSCRIPT_EM_X_SIZE:- *position = font->x_scale * 10 / 12;+ *position = hb_clamp_to<hb_position_t> ((int64_t) font->x_scale * 10 / 12);break;case HB_OT_METRICS_TAG_SUBSCRIPT_EM_Y_SIZE:case HB_OT_METRICS_TAG_SUPERSCRIPT_EM_Y_SIZE:- *position = font->y_scale * 10 / 12;+ *position = hb_clamp_to<hb_position_t> ((int64_t) font->y_scale * 10 / 12);break;case HB_OT_METRICS_TAG_SUBSCRIPT_EM_X_OFFSET:diff --git a/thirdparty/harfbuzz/src/hb-ot-os2-table.hh b/thirdparty/harfbuzz/src/hb-ot-os2-table.hhindex 1ae0da1267d..db8fd4d8795 100644--- a/thirdparty/harfbuzz/src/hb-ot-os2-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-os2-table.hh@@ -346,10 +346,10 @@ struct OS2size_t get_size () const{- unsigned result = min_size;- if (version >= 1) result += v1X.get_size ();- if (version >= 2) result += v2X.get_size ();- if (version >= 5) result += v5X.get_size ();+ size_t result = min_size;+ if (version >= 1) result = hb_unsigned_add_saturate (result, v1X.get_size ());+ if (version >= 2) result = hb_unsigned_add_saturate (result, v2X.get_size ());+ if (version >= 5) result = hb_unsigned_add_saturate (result, v5X.get_size ());return result;}diff --git a/thirdparty/harfbuzz/src/hb-ot-post-table.hh b/thirdparty/harfbuzz/src/hb-ot-post-table.hhindex 3741f13d038..d89a4547537 100644--- a/thirdparty/harfbuzz/src/hb-ot-post-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-post-table.hh@@ -188,7 +188,7 @@ struct postif (unlikely (!gids)){- gids = (uint16_t *) hb_malloc (count * sizeof (gids[0]));+ gids = (uint16_t *) hb_malloc2 (count, sizeof (gids[0]));if (unlikely (!gids))return false; /* Anything better?! */@@ -197,7 +197,10 @@ struct postauto thiz = this;hb_array_t<uint16_t> (gids, count).qsort ([thiz] (const uint16_t &a, const uint16_t &b) {- return thiz->find_glyph_name (a).cmp (thiz->find_glyph_name (b)) > 0;+ /* hb_array_t::cmp has reversed argument order, so+ * x.cmp(y) returns sign of (y - x). Pass (b, a) to+ * get standard "negative when a < b" ordering. */+ return thiz->find_glyph_name (b).cmp (thiz->find_glyph_name (a));});if (unlikely (!gids_sorted_by_name.cmpexch (nullptr, gids)))diff --git a/thirdparty/harfbuzz/src/hb-ot-shape-fallback.cc b/thirdparty/harfbuzz/src/hb-ot-shape-fallback.ccindex ce7e0c03b47..acf55c76a6b 100644--- a/thirdparty/harfbuzz/src/hb-ot-shape-fallback.cc+++ b/thirdparty/harfbuzz/src/hb-ot-shape-fallback.cc@@ -197,8 +197,10 @@ zero_mark_advances (hb_buffer_t *buffer,{if (adjust_offsets_when_zeroing){- buffer->pos[i].x_offset -= buffer->pos[i].x_advance;- buffer->pos[i].y_offset -= buffer->pos[i].y_advance;+ buffer->pos[i].x_offset = hb_saturate_sub (buffer->pos[i].x_offset,+ buffer->pos[i].x_advance);+ buffer->pos[i].y_offset = hb_saturate_sub (buffer->pos[i].y_offset,+ buffer->pos[i].y_advance);}buffer->pos[i].x_advance = 0;buffer->pos[i].y_advance = 0;@@ -231,10 +233,12 @@ position_mark (const hb_ot_shape_plan_t *plan HB_UNUSED,case HB_UNICODE_COMBINING_CLASS_DOUBLE_BELOW:case HB_UNICODE_COMBINING_CLASS_DOUBLE_ABOVE:if (buffer->props.direction == HB_DIRECTION_LTR) {- pos.x_offset += base_extents.x_bearing + base_extents.width - mark_extents.width / 2 - mark_extents.x_bearing;+ pos.x_offset = hb_clamp_to<hb_position_t> ((int64_t) base_extents.x_bearing + base_extents.width -+ mark_extents.width / 2 - mark_extents.x_bearing);break;} else if (buffer->props.direction == HB_DIRECTION_RTL) {- pos.x_offset += base_extents.x_bearing - mark_extents.width / 2 - mark_extents.x_bearing;+ pos.x_offset = hb_clamp_to<hb_position_t> ((int64_t) base_extents.x_bearing -+ mark_extents.width / 2 - mark_extents.x_bearing);break;}HB_FALLTHROUGH;@@ -245,21 +249,24 @@ position_mark (const hb_ot_shape_plan_t *plan HB_UNUSED,case HB_UNICODE_COMBINING_CLASS_BELOW:case HB_UNICODE_COMBINING_CLASS_ABOVE:/* Center align. */- pos.x_offset += base_extents.x_bearing + (base_extents.width - mark_extents.width) / 2 - mark_extents.x_bearing;+ pos.x_offset = hb_clamp_to<hb_position_t> ((int64_t) base_extents.x_bearing ++ ((int64_t) base_extents.width - mark_extents.width) / 2 -+ mark_extents.x_bearing);break;case HB_UNICODE_COMBINING_CLASS_ATTACHED_BELOW_LEFT:case HB_UNICODE_COMBINING_CLASS_BELOW_LEFT:case HB_UNICODE_COMBINING_CLASS_ABOVE_LEFT:/* Left align. */- pos.x_offset += base_extents.x_bearing - mark_extents.x_bearing;+ pos.x_offset = hb_saturate_sub (base_extents.x_bearing, mark_extents.x_bearing);break;case HB_UNICODE_COMBINING_CLASS_ATTACHED_ABOVE_RIGHT:case HB_UNICODE_COMBINING_CLASS_BELOW_RIGHT:case HB_UNICODE_COMBINING_CLASS_ABOVE_RIGHT:/* Right align. */- pos.x_offset += base_extents.x_bearing + base_extents.width - mark_extents.width - mark_extents.x_bearing;+ pos.x_offset = hb_clamp_to<hb_position_t> ((int64_t) base_extents.x_bearing + base_extents.width -+ mark_extents.width - mark_extents.x_bearing);break;}@@ -271,19 +278,20 @@ position_mark (const hb_ot_shape_plan_t *plan HB_UNUSED,case HB_UNICODE_COMBINING_CLASS_BELOW:case HB_UNICODE_COMBINING_CLASS_BELOW_RIGHT:/* Add gap, fall-through. */- base_extents.height -= y_gap;+ base_extents.height = hb_saturate_sub (base_extents.height, y_gap);HB_FALLTHROUGH;case HB_UNICODE_COMBINING_CLASS_ATTACHED_BELOW_LEFT:case HB_UNICODE_COMBINING_CLASS_ATTACHED_BELOW:- pos.y_offset = base_extents.y_bearing + base_extents.height - mark_extents.y_bearing;+ pos.y_offset = hb_clamp_to<hb_position_t> ((int64_t) base_extents.y_bearing ++ base_extents.height - mark_extents.y_bearing);/* Never shift up "below" marks. */if ((y_gap > 0) == (pos.y_offset > 0)){- base_extents.height -= pos.y_offset;+ base_extents.height = hb_saturate_sub (base_extents.height, pos.y_offset);pos.y_offset = 0;}- base_extents.height += mark_extents.height;+ base_extents.height = hb_saturate_add (base_extents.height, mark_extents.height);break;case HB_UNICODE_COMBINING_CLASS_DOUBLE_ABOVE:@@ -291,23 +299,24 @@ position_mark (const hb_ot_shape_plan_t *plan HB_UNUSED,case HB_UNICODE_COMBINING_CLASS_ABOVE:case HB_UNICODE_COMBINING_CLASS_ABOVE_RIGHT:/* Add gap, fall-through. */- base_extents.y_bearing += y_gap;- base_extents.height -= y_gap;+ base_extents.y_bearing = hb_saturate_add (base_extents.y_bearing, y_gap);+ base_extents.height = hb_saturate_sub (base_extents.height, y_gap);HB_FALLTHROUGH;case HB_UNICODE_COMBINING_CLASS_ATTACHED_ABOVE:case HB_UNICODE_COMBINING_CLASS_ATTACHED_ABOVE_RIGHT:- pos.y_offset = base_extents.y_bearing - (mark_extents.y_bearing + mark_extents.height);+ pos.y_offset = hb_clamp_to<hb_position_t> ((int64_t) base_extents.y_bearing -+ mark_extents.y_bearing - mark_extents.height);/* Don't shift down "above" marks too much. */if ((y_gap > 0) != (pos.y_offset > 0)){- int correction = -pos.y_offset / 2;- base_extents.y_bearing += correction;- base_extents.height -= correction;- pos.y_offset += correction;+ hb_position_t correction = -(pos.y_offset / 2);+ base_extents.y_bearing = hb_saturate_add (base_extents.y_bearing, correction);+ base_extents.height = hb_saturate_sub (base_extents.height, correction);+ pos.y_offset = hb_saturate_add (pos.y_offset, correction);}- base_extents.y_bearing -= mark_extents.height;- base_extents.height += mark_extents.height;+ base_extents.y_bearing = hb_saturate_sub (base_extents.y_bearing, mark_extents.height);+ base_extents.height = hb_saturate_add (base_extents.height, mark_extents.height);break;}}@@ -332,7 +341,8 @@ position_around_base (const hb_ot_shape_plan_t *plan,zero_mark_advances (buffer, base + 1, end, adjust_offsets_when_zeroing);return;}- base_extents.y_bearing += buffer->pos[base].y_offset;+ base_extents.y_bearing = hb_saturate_add (base_extents.y_bearing,+ buffer->pos[base].y_offset);/* Use horizontal advance for horizontal positioning.* Generally a better idea. Also works for zero-ink glyphs. See:* https://github.com/harfbuzz/harfbuzz/issues/1532 */@@ -346,8 +356,8 @@ position_around_base (const hb_ot_shape_plan_t *plan,hb_position_t x_offset = 0, y_offset = 0;if (HB_DIRECTION_IS_FORWARD (buffer->props.direction)) {- x_offset -= buffer->pos[base].x_advance;- y_offset -= buffer->pos[base].y_advance;+ x_offset = hb_saturate_neg (buffer->pos[base].x_advance);+ y_offset = hb_saturate_neg (buffer->pos[base].y_advance);}hb_glyph_extents_t component_extents = base_extents;@@ -376,9 +386,13 @@ position_around_base (const hb_ot_shape_plan_t *plan,horiz_dir = hb_script_get_horizontal_direction (plan->props.script);}if (horiz_dir == HB_DIRECTION_LTR)- component_extents.x_bearing += (this_lig_component * component_extents.width) / num_lig_components;+ component_extents.x_bearing = hb_clamp_to<hb_position_t> (+ (int64_t) component_extents.x_bearing ++ (int64_t) this_lig_component * component_extents.width / num_lig_components);else- component_extents.x_bearing += ((num_lig_components - 1 - this_lig_component) * component_extents.width) / num_lig_components;+ component_extents.x_bearing = hb_clamp_to<hb_position_t> (+ (int64_t) component_extents.x_bearing ++ (int64_t) (num_lig_components - 1 - this_lig_component) * component_extents.width / num_lig_components);component_extents.width /= num_lig_components;}}@@ -394,16 +408,16 @@ position_around_base (const hb_ot_shape_plan_t *plan,buffer->pos[i].x_advance = 0;buffer->pos[i].y_advance = 0;- buffer->pos[i].x_offset += x_offset;- buffer->pos[i].y_offset += y_offset;+ buffer->pos[i].x_offset = hb_saturate_add (buffer->pos[i].x_offset, x_offset);+ buffer->pos[i].y_offset = hb_saturate_add (buffer->pos[i].y_offset, y_offset);} else {if (HB_DIRECTION_IS_FORWARD (buffer->props.direction)) {- x_offset -= buffer->pos[i].x_advance;- y_offset -= buffer->pos[i].y_advance;+ x_offset = hb_saturate_sub (x_offset, buffer->pos[i].x_advance);+ y_offset = hb_saturate_sub (y_offset, buffer->pos[i].y_advance);} else {- x_offset += buffer->pos[i].x_advance;- y_offset += buffer->pos[i].y_advance;+ x_offset = hb_saturate_add (x_offset, buffer->pos[i].x_advance);+ y_offset = hb_saturate_add (y_offset, buffer->pos[i].y_advance);}}}@@ -559,7 +573,7 @@ _hb_ot_shape_fallback_spaces (const hb_ot_shape_plan_t *plan HB_UNUSED,if (horizontal)pos[i].x_advance = +font->x_scale / 4;else- pos[i].y_advance = -font->y_scale / 4;+ pos[i].y_advance = -(int64_t) font->y_scale / 4;}hb_unicode_funcs_t::space_t space_type = _hb_glyph_info_get_unicode_space_fallback_type (&info[i]);@@ -579,16 +593,16 @@ _hb_ot_shape_fallback_spaces (const hb_ot_shape_plan_t *plan HB_UNUSED,case t::SPACE_EM_6:case t::SPACE_EM_16:if (horizontal)- pos[i].x_advance = +(font->x_scale + ((int) space_type)/2) / (int) space_type;+ pos[i].x_advance = ((int64_t) font->x_scale + ((int) space_type)/2) / (int) space_type;else- pos[i].y_advance = -(font->y_scale + ((int) space_type)/2) / (int) space_type;+ pos[i].y_advance = -((int64_t) font->y_scale + ((int) space_type)/2) / (int) space_type;break;case t::SPACE_4_EM_18:if (horizontal)- pos[i].x_advance = (int64_t) +font->x_scale * 4 / 18;+ pos[i].x_advance = (int64_t) font->x_scale * 4 / 18;else- pos[i].y_advance = (int64_t) -font->y_scale * 4 / 18;+ pos[i].y_advance = -(int64_t) font->y_scale * 4 / 18;break;case t::SPACE_FIGURE:diff --git a/thirdparty/harfbuzz/src/hb-ot-shape.cc b/thirdparty/harfbuzz/src/hb-ot-shape.ccindex c4027c4a78f..691642402d1 100644--- a/thirdparty/harfbuzz/src/hb-ot-shape.cc+++ b/thirdparty/harfbuzz/src/hb-ot-shape.cc@@ -922,7 +922,10 @@ hb_ot_substitute_plan (const hb_ot_shape_context_t *c){hb_aat_layout_substitute (c->plan, c->font, c->buffer,c->user_features, c->num_user_features);- c->buffer->update_digest ();+ /* The buffer digest is only used by the OT lookup-apply loop;+ * without GPOS ahead, nothing consumes it. */+ if (c->plan->apply_gpos)+ c->buffer->update_digest ();}else#endif@@ -973,8 +976,8 @@ hb_ot_substitute_post (const hb_ot_shape_context_t *c)static inline voidadjust_mark_offsets (hb_glyph_position_t *pos){- pos->x_offset -= pos->x_advance;- pos->y_offset -= pos->y_advance;+ pos->x_offset = hb_saturate_sub (pos->x_offset, pos->x_advance);+ pos->y_offset = hb_saturate_sub (pos->y_offset, pos->y_advance);}static inline voiddiff --git a/thirdparty/harfbuzz/src/hb-ot-shaper-arabic-fallback.hh b/thirdparty/harfbuzz/src/hb-ot-shaper-arabic-fallback.hhindex b82de35aac5..ef90cb4fed4 100644--- a/thirdparty/harfbuzz/src/hb-ot-shaper-arabic-fallback.hh+++ b/thirdparty/harfbuzz/src/hb-ot-shaper-arabic-fallback.hh@@ -231,11 +231,7 @@ struct arabic_fallback_plan_tOT::hb_ot_layout_lookup_accelerator_t *accel_array[ARABIC_FALLBACK_MAX_LOOKUPS];};-#if defined(_WIN32) && !defined(HB_NO_WIN1256)-#define HB_WITH_WIN1256-#endif--#ifdef HB_WITH_WIN1256+#ifndef HB_NO_WIN1256#include "hb-ot-shaper-arabic-win1256.hh"#endif@@ -254,7 +250,7 @@ arabic_fallback_plan_init_win1256 (arabic_fallback_plan_t *fallback_plan HB_UNUSconst hb_ot_shape_plan_t *plan HB_UNUSED,hb_font_t *font HB_UNUSED){-#ifdef HB_WITH_WIN1256+#ifndef HB_NO_WIN1256/* Does this font look like it's Windows-1256-encoded? */hb_codepoint_t g;if (!(hb_font_get_glyph (font, 0x0627u, 0, &g) && g == 199 /* ALEF */ &&diff --git a/thirdparty/harfbuzz/src/hb-ot-shaper-arabic-pua.hh b/thirdparty/harfbuzz/src/hb-ot-shaper-arabic-pua.hhindex 7464e5d8a3b..dbbee473fcf 100644--- a/thirdparty/harfbuzz/src/hb-ot-shaper-arabic-pua.hh+++ b/thirdparty/harfbuzz/src/hb-ot-shaper-arabic-pua.hh@@ -2,7 +2,7 @@/** The following table is generated by running:*- * ./gen-arabic-pua.py+ * ./gen-arabic-pua.py ArabicPUASimplified.txt ArabicPUATraditional.txt**/@@ -37,15 +37,15 @@ static const uint8_t _hb_arabic_pua_u8[453]=33, 0, 0, 0, 0, 0, 0, 0, 34, 0, 0, 0, 35, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 36, 37, 38, 0, 0, 0, 0, 0, 0,0, 39, 0, 0, 40, 41, 42, 0, 43, 44, 0, 0, 45, 46, 0, 47,- 48, 49, 0, 0, 0, 0, 50, 0, 0, 51, 52, 0, 53, 54, 55, 56,- 57, 58, 0, 0, 0, 0, 0, 59, 60, 61, 62, 63, 64, 0, 0, 0,+ 48, 49, 0, 0, 0, 0, 0, 0, 0, 50, 51, 0, 52, 53, 54, 55,+ 56, 57, 0, 0, 0, 0, 0, 58, 59, 60, 61, 62, 63, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 65, 0, 0, 66, 0, 0, 67, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,- 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,- 95, 96, 97, 98, 99,+ 0, 64, 0, 0, 65, 0, 0, 66, 0, 0, 0, 0, 0, 0, 0, 0,+ 0, 0, 0, 0, 0, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,+ 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93,+ 94, 95, 96, 97, 98,};-static const uint16_t _hb_arabic_pua_u16[717]=+static const uint16_t _hb_arabic_pua_u16[713]={0, 0, 0, 0, 0, 0, 0, 0,61728,61729,61730, 0, 0,61733, 0, 0,61736,61737,61738,61739,61790,61741,61742,61743,61872,61873,61874,61875,61876,61877,61878,61879,@@ -77,21 +77,21 @@ static const uint16_t _hb_arabic_pua_u16[717]=61952,61952,61952,61952, 0,62000,62001,62002,62003,62004,62005,62006,62007,62008,62009, 0,62046,62046, 0, 0, 0,61964,61965,61966,61967,62012,62014, 0, 0,61954, 0,61981,0, 0, 0,61955, 0,61982, 0,61956, 0, 0, 0,62111, 0, 0, 0, 0,- 61970,61971,61972,61957, 0,61980, 0, 0, 0, 0, 0,61958, 0,61983, 0, 0,+ 61970,61971,61972,61957,62101,61980, 0, 0, 0, 0, 0,61958, 0,61983, 0, 0,0, 0, 0,62191, 0,62188,62189,62192, 0, 0, 0,61973, 0, 0,62098, 0,- 0,61974, 0, 0,62099, 0, 0,62101, 0, 0,61975, 0, 0,62100, 0, 0,- 0,62080,62081,62082,62102, 0,62083,62084,62085,62103, 0, 0, 0,62106, 0,62107,- 0,62108, 0, 0, 0,61976, 0, 0, 0, 0,62086,62087,62088,62109,61978,62089,- 62090,62091,62110,62093,62094, 0,62104, 0, 0, 0, 0,62095,62096,62097,62105, 0,- 0,61977, 0, 0, 0, 0, 0,62075,62077,61968, 0, 0, 0, 0,62021,62022,- 62019,62020,62170,62171,62023,62024,62169,62168,62166,62167,62017,62018,62028,62027,62025,62026,- 62161,62162,62032,62031,62029,62030,62036,62035,62033,62034,62040,62039,62037,62038,62048,62044,- 62041,62042,62052,62051,62049,62050,62053,62054,62055,62056,62057,62058,62059,62060,62064,62063,- 62061,62062,62068,62067,62065,62066,62072,62071,62069,62070,62078,62076,62073,62074,62114,62113,- 62079,62193,62118,62117,62115,62116,62122,62121,62119,62120,62126,62125,62123,62124,62130,62129,- 62127,62128,62134,62133,62131,62132,62138,62137,62135,62136,62142,62141,62139,62140,62146,62145,- 62143,62144,62150,62149,62147,62148,62154,62153,62151,62152,62155,62156,62164,62163,62160,62159,- 62157,62158,62176,62177,62174,62175,62178,62179,62172,62173, 0, 0, 0,+ 0,61974, 0, 0,62099, 0,61975, 0, 0,62100, 0, 0, 0,62080,62081,62082,+ 62102, 0,62083,62084,62085,62103, 0, 0, 0,62106, 0,62107, 0,62108, 0, 0,+ 0,61976, 0, 0, 0, 0,62086,62087,62088,62109,61978,62089,62090,62091,62110,62093,+ 62094, 0,62104, 0, 0, 0, 0,62095,62096,62097,62105, 0, 0,61977, 0, 0,+ 0, 0, 0,62075,62077,61968, 0, 0, 0, 0,62021,62022,62019,62020,62170,62171,+ 62023,62024,62169,62168,62166,62167,62017,62018,62028,62027,62025,62026,62161,62162,62032,62031,+ 62029,62030,62036,62035,62033,62034,62040,62039,62037,62038,62048,62044,62041,62042,62052,62051,+ 62049,62050,62053,62054,62055,62056,62057,62058,62059,62060,62064,62063,62061,62062,62068,62067,+ 62065,62066,62072,62071,62069,62070,62078,62076,62073,62074,62114,62113,62079,62193,62118,62117,+ 62115,62116,62122,62121,62119,62120,62126,62125,62123,62124,62130,62129,62127,62128,62134,62133,+ 62131,62132,62138,62137,62135,62136,62142,62141,62139,62140,62146,62145,62143,62144,62150,62149,+ 62147,62148,62154,62153,62151,62152,62155,62156,62164,62163,62160,62159,62157,62158,62176,62177,+ 62174,62175,62178,62179,62172,62173, 0, 0, 0,};static inline uint8_t _hb_arabic_pua_b4 (const uint8_t* a, unsigned i)diff --git a/thirdparty/harfbuzz/src/hb-ot-shaper-arabic-table.hh b/thirdparty/harfbuzz/src/hb-ot-shaper-arabic-table.hhindex 39da24b8be6..33e5bd2f851 100644--- a/thirdparty/harfbuzz/src/hb-ot-shaper-arabic-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-shaper-arabic-table.hh@@ -280,7 +280,7 @@ static const struct ligature_set_t {struct ligature_pairs_t {uint16_t components[1];uint16_t ligature;- } ligatures[14];+ } ligatures[15];} ligature_table[] ={{ 0xFE91u, {@@ -337,6 +337,7 @@ static const struct ligature_set_t {{ {0xFEA8u}, 0xFCCBu }, /* ARABIC LIGATURE LAM WITH KHAH INITIAL FORM */{ {0xFEE2u}, 0xFC42u }, /* ARABIC LIGATURE LAM WITH MEEM ISOLATED FORM */{ {0xFEE4u}, 0xFCCCu }, /* ARABIC LIGATURE LAM WITH MEEM INITIAL FORM */+ { {0xFEF0u}, 0xFC43u }, /* ARABIC LIGATURE LAM WITH ALEF MAKSURA ISOLATED FORM */{ {0xFEF2u}, 0xFC44u }, /* ARABIC LIGATURE LAM WITH YEH ISOLATED FORM */{ {0xFEECu}, 0xFCCDu }, /* ARABIC LIGATURE LAM WITH HEH INITIAL FORM */{ {0xFE82u}, 0xFEF5u }, /* ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE ISOLATED FORM */diff --git a/thirdparty/harfbuzz/src/hb-ot-shaper-arabic.cc b/thirdparty/harfbuzz/src/hb-ot-shaper-arabic.ccindex d33b9099ec9..a641a53f313 100644--- a/thirdparty/harfbuzz/src/hb-ot-shaper-arabic.cc+++ b/thirdparty/harfbuzz/src/hb-ot-shaper-arabic.cc@@ -534,12 +534,12 @@ apply_stch (const hb_ot_shape_plan_t *plan HB_UNUSED,hb_position_t width = font->get_glyph_h_advance (info[i].codepoint);if (info[i].arabic_shaping_action() == STCH_FIXED){- w_fixed += width;+ w_fixed = hb_saturate_add (w_fixed, width);n_fixed++;}else{- w_repeating += width;+ w_repeating = hb_saturate_add (w_repeating, width);n_repeating++;}}@@ -551,7 +551,7 @@ apply_stch (const hb_ot_shape_plan_t *plan HB_UNUSED,HB_ARABIC_GENERAL_CATEGORY_IS_WORD (_hb_glyph_info_get_general_category (&info[context - 1])))){context--;- w_total += pos[context].x_advance;+ w_total = hb_saturate_add (w_total, pos[context].x_advance);}i++; // Don't touch i again.@@ -573,7 +573,7 @@ apply_stch (const hb_ot_shape_plan_t *plan HB_UNUSED,w_remaining_signed = -w_remaining_signed;w_repeating_signed = -w_repeating_signed;}- hb_position_t w_remaining = (hb_position_t) (w_total - w_fixed);+ hb_position_t w_remaining = hb_saturate_sub (w_total, w_fixed);if (w_remaining_signed > w_repeating_signed && w_repeating_signed > 0)n_copies = w_remaining_signed / w_repeating_signed - 1;@@ -586,7 +586,7 @@ apply_stch (const hb_ot_shape_plan_t *plan HB_UNUSED,int64_t excess = (n_copies + 1) * w_repeating_signed - w_remaining_signed;if (excess > 0){- extra_repeat_overlap = excess / (n_copies * n_repeating);+ extra_repeat_overlap = hb_clamp_to<hb_position_t> (excess / ((int64_t) n_copies * (int64_t) n_repeating));w_remaining = 0;}}@@ -630,9 +630,9 @@ apply_stch (const hb_ot_shape_plan_t *plan HB_UNUSED,{if (rtl){- x_offset -= width;+ x_offset = hb_saturate_sub (x_offset, width);if (n > 0)- x_offset += extra_repeat_overlap;+ x_offset = hb_saturate_add (x_offset, extra_repeat_overlap);}pos[k - 1].x_offset = x_offset;/* Append copy. */@@ -642,9 +642,9 @@ apply_stch (const hb_ot_shape_plan_t *plan HB_UNUSED,if (!rtl){- x_offset += width;+ x_offset = hb_saturate_add (x_offset, width);if (n > 0)- x_offset -= extra_repeat_overlap;+ x_offset = hb_saturate_sub (x_offset, extra_repeat_overlap);}}}diff --git a/thirdparty/harfbuzz/src/hb-ot-shaper-hangul.cc b/thirdparty/harfbuzz/src/hb-ot-shaper-hangul.ccindex ce87a915645..514b078bf88 100644--- a/thirdparty/harfbuzz/src/hb-ot-shaper-hangul.cc+++ b/thirdparty/harfbuzz/src/hb-ot-shaper-hangul.cc@@ -67,14 +67,23 @@ static voidoverride_features_hangul (hb_ot_shape_planner_t *plan){/* Uniscribe does not apply 'calt' for Hangul, and certain fonts- * (Noto Sans CJK, Source Sans Han, etc) apply all of jamo lookups- * in calt, which is not desirable. */- plan->map.disable_feature (HB_TAG('c','a','l','t'));+ * (Noto Sans CJK, Source Han Sans, etc) apply all of jamo lookups+ * in calt, which is not desirable.+ *+ * Rather than disabling 'calt' for the entire run, which also turns+ * it off for any other characters in the run, allocate a mask for it+ * and clear that mask on jamo only (in setup_masks_hangul). That+ * keeps jamo out of reach of such lookups while letting the rest of+ * the run shape with 'calt' as usual.+ *+ * https://github.com/harfbuzz/harfbuzz/discussions/4853 */+ plan->map.add_feature (HB_TAG('c','a','l','t'));}struct hangul_shape_plan_t{hb_mask_t mask_array[HANGUL_FEATURE_COUNT];+ hb_mask_t calt_mask;};static void *@@ -87,6 +96,8 @@ data_create_hangul (const hb_ot_shape_plan_t *plan)for (unsigned int i = 0; i < HANGUL_FEATURE_COUNT; i++)hangul_plan->mask_array[i] = plan->map.get_1_mask (hangul_features[i]);+ hangul_plan->calt_mask = plan->map.get_1_mask (HB_TAG('c','a','l','t'));+return hangul_plan;}@@ -405,7 +416,14 @@ setup_masks_hangul (const hb_ot_shape_plan_t *plan,unsigned int count = buffer->len;hb_glyph_info_t *info = buffer->info;for (unsigned int i = 0; i < count; i++, info++)+ {info->mask |= hangul_plan->mask_array[info->hangul_shaping_feature()];++ /* Keep 'calt' away from jamo; see override_features_hangul(). */+ hb_codepoint_t u = info->codepoint;+ if (isL (u) || isV (u) || isT (u))+ info->mask &= ~hangul_plan->calt_mask;+ }}HB_BUFFER_DEALLOCATE_VAR (buffer, hangul_shaping_feature);diff --git a/thirdparty/harfbuzz/src/hb-ot-tag-table.hh b/thirdparty/harfbuzz/src/hb-ot-tag-table.hhindex 124599e7cca..294124c4864 100644--- a/thirdparty/harfbuzz/src/hb-ot-tag-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-tag-table.hh@@ -7,7 +7,7 @@* on files with these headers:** <meta name="updated_at" content="2024-12-06T06:35:00Z" />- * File-Date: 2025-08-25+ * File-Date: 2026-06-14*/#ifndef HB_OT_TAG_TABLE_HH@@ -82,7 +82,7 @@ static const LangTag ot_languages2[] = {{HB_TAG('h','y',' ',' '), HB_TAG('H','Y','E','0')}, /* Armenian -> Armenian East */{HB_TAG('h','y',' ',' '), HB_TAG('H','Y','E',' ')}, /* Armenian */{HB_TAG('h','z',' ',' '), HB_TAG('H','E','R',' ')}, /* Herero */- {HB_TAG('i','a',' ',' '), HB_TAG('I','N','A',' ')}, /* Interlingua (International Auxiliary Language Association) */+ {HB_TAG('i','a',' ',' '), HB_TAG('I','N','A',' ')}, /* Interlingua (IALA) */{HB_TAG('i','d',' ',' '), HB_TAG('I','N','D',' ')}, /* Indonesian */{HB_TAG('i','d',' ',' '), HB_TAG('M','L','Y',' ')}, /* Indonesian -> Malay */{HB_TAG('i','e',' ',' '), HB_TAG('I','L','E',' ')}, /* Interlingue */@@ -834,7 +834,7 @@ static const LangTag ot_languages3[] = {{HB_TAG('m','c','m',' '), HB_TAG('C','P','P',' ')}, /* Malaccan Creole Portuguese -> Creoles */{HB_TAG('m','c','t',' '), HB_TAG('B','T','I',' ')}, /* Mengisa -> Beti */{HB_TAG('m','d','f',' '), HB_TAG('M','O','K',' ')}, /* Moksha */- {HB_TAG('m','d','y',' '), HB_TAG('M','L','E',' ')}, /* Male (Ethiopia) */+ {HB_TAG('m','d','y',' '), HB_TAG('M','L','E',' ')}, /* Male */{HB_TAG('m','e','n',' '), HB_TAG('M','D','E',' ')}, /* Mende (Sierra Leone) */{HB_TAG('m','e','o',' '), HB_TAG('M','L','Y',' ')}, /* Kedah Malay -> Malay */{HB_TAG('m','f','b',' '), HB_TAG('M','L','Y',' ')}, /* Bangka -> Malay */@@ -1040,7 +1040,7 @@ static const LangTag ot_languages3[] = {{HB_TAG('s','r','m',' '), HB_TAG('C','P','P',' ')}, /* Saramaccan -> Creoles */{HB_TAG('s','r','n',' '), HB_TAG('C','P','P',' ')}, /* Sranan Tongo -> Creoles */{HB_TAG('s','r','o',' '), HB_TAG('S','R','D',' ')}, /* Campidanese Sardinian -> Sardinian */- {HB_TAG('s','r','s',' '), HB_TAG('A','T','H',' ')}, /* Sarsi -> Athapaskan */+ {HB_TAG('s','r','s',' '), HB_TAG('A','T','H',' ')}, /* Tsuut'ina -> Athapaskan */{HB_TAG('s','s','h',' '), HB_TAG('A','R','A',' ')}, /* Shihhi Arabic -> Arabic */{HB_TAG('s','t','a',' '), HB_TAG('C','P','P',' ')}, /* Settla -> Creoles */{HB_TAG('s','t','v',' '), HB_TAG('S','I','G',' ')}, /* Silt'e -> Silte Gurage */@@ -1236,8 +1236,8 @@ static const hb_tag_t ot_languages3_multi_values[] = {HB_TAG('D','C','R',' '), /* Woods Cree */HB_TAG('T','C','R',' '), /* Woods Cree -> TH-Cree */HB_TAG('C','R','E',' '), /* Woods Cree -> Cree */- HB_TAG('S','L','A',' '), /* Slave (Athapascan) [macrolanguage] -> Slavey */- HB_TAG('A','T','H',' '), /* Slave (Athapascan) [macrolanguage] -> Athapaskan */+ HB_TAG('S','L','A',' '), /* Slavey [macrolanguage] */+ HB_TAG('A','T','H',' '), /* Slavey [macrolanguage] -> Athapaskan */HB_TAG('D','G','O',' '), /* Dogri (individual language) */HB_TAG('D','G','R',' '), /* Dogri (macrolanguage) */HB_TAG('D','I','Q',' '), /* Dimli */@@ -1490,7 +1490,7 @@ static const LangTagRange ot_languages3_multi[] = {{HB_TAG('c','r','x',' '), 59, 2}, /* Carrier */{HB_TAG('c','s','w',' '), 61, 3}, /* Swampy Cree -> N-Cree */{HB_TAG('c','w','d',' '), 64, 3}, /* Woods Cree */- {HB_TAG('d','e','n',' '), 67, 2}, /* Slave (Athapascan) [macrolanguage] -> Slavey */+ {HB_TAG('d','e','n',' '), 67, 2}, /* Slavey [macrolanguage] */{HB_TAG('d','g','o',' '), 69, 2}, /* Dogri (individual language) */{HB_TAG('d','i','q',' '), 71, 2}, /* Dimli */{HB_TAG('d','r','w',' '), 73, 2}, /* Darwazi (retired code) -> Dari */diff --git a/thirdparty/harfbuzz/src/hb-ot-tag.cc b/thirdparty/harfbuzz/src/hb-ot-tag.ccindex 900f37ab428..807de522cd7 100644--- a/thirdparty/harfbuzz/src/hb-ot-tag.cc+++ b/thirdparty/harfbuzz/src/hb-ot-tag.cc@@ -43,8 +43,10 @@ hb_ot_old_tag_from_script (hb_script_t script)case HB_SCRIPT_INVALID: return HB_OT_TAG_DEFAULT_SCRIPT;case HB_SCRIPT_MATH: return HB_OT_TAG_MATH_SCRIPT;- /* KATAKANA and HIRAGANA both map to 'kana' */+ /* Hiragana, Katakana, and their collective ISO 15924 script all map to 'kana'. */case HB_SCRIPT_HIRAGANA: return HB_TAG('k','a','n','a');+ case HB_TAG('H','r','k','t'):+ return HB_TAG('k','a','n','a');/* Spaces at the end are preserved, unlike ISO 15924 */case HB_SCRIPT_LAO: return HB_TAG('l','a','o',' ');@@ -666,10 +668,10 @@ hb_ot_tags_to_script_and_language (hb_tag_t script_tag,primary_script_tag,nullptr, nullptr);*language = hb_ot_tag_to_language (language_tag);- if (script_count == 0 || primary_script_tag[0] != script_tag)+ const char *lang_str = *language ? hb_language_to_string (*language) : nullptr;+ if (lang_str && (script_count == 0 || primary_script_tag[0] != script_tag)){unsigned char *buf;- const char *lang_str = hb_language_to_string (*language);size_t len = strlen (lang_str);buf = (unsigned char *) hb_malloc (len + 16);if (unlikely (!buf))diff --git a/thirdparty/harfbuzz/src/hb-ot-var-avar-table.hh b/thirdparty/harfbuzz/src/hb-ot-var-avar-table.hhindex 98ce46e61df..9a45a00b624 100644--- a/thirdparty/harfbuzz/src/hb-ot-var-avar-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-var-avar-table.hh@@ -29,6 +29,7 @@#include "hb-open-type.hh"#include "hb-ot-var-common.hh"+#include "hb-ot-var-fvar-table.hh"/*@@ -220,10 +221,10 @@ struct SegmentMaps : Array16Of<AxisValueMap>if (value < map[i].fromCoord)break;- if (i == 0)+ if (i == start){// Value before all segments; Shift.- return value - map[0].fromCoord + map[0].toCoord;+ return value - map[start].fromCoord + map[start].toCoord;}if (i == end){@@ -254,7 +255,8 @@ struct SegmentMaps : Array16Of<AxisValueMap>return Triple{(double) unmapped_min, (double) unmapped_middle, (double) unmapped_max};}- bool subset (hb_subset_context_t *c, hb_tag_t axis_tag) const+ bool subset (hb_subset_context_t *c, hb_tag_t axis_tag,+ hb_vector_t<AxisValueMap> *out_mappings = nullptr) const{TRACE_SUBSET (this);@@ -262,9 +264,14 @@ struct SegmentMaps : Array16Of<AxisValueMap>* We should instead keep the design coords in the shape plan and use* those. unmap_axis_range needs to be killed. */- /* avar mapped normalized axis range*/+ /* avar mapped normalized axis range. Under avar2, axes_location holds+ * only the self-contained pins for the other tables; avar itself uses+ * the intermediate-space ranges of all restricted axes. */+ const auto &axes_location = c->plan->has_avar2+ ? c->plan->old_intermediates+ : c->plan->axes_location;Triple *axis_range;- if (!c->plan->axes_location.has (axis_tag, &axis_range))+ if (!axes_location.has (axis_tag, &axis_range))return c->serializer->embed (*this);TripleDistances *axis_triple_distances;@@ -304,18 +311,185 @@ struct SegmentMaps : Array16Of<AxisValueMap>value_mappings.qsort ();+ if (unlikely (value_mappings.in_error ()))+ return_trace (false);+for (const auto& _ : value_mappings){if (!_.serialize (c->serializer))return_trace (false);}- return_trace (c->serializer->check_assign (out->len, value_mappings.length, HB_SERIALIZE_ERROR_INT_OVERFLOW));+ if (!c->serializer->check_assign (out->len, value_mappings.length, HB_SERIALIZE_ERROR_INT_OVERFLOW))+ return_trace (false);+ /* Hand the instantiated mappings to the caller; avar2 offset+ * compensation needs them to locate the new mapping's kinks. */+ if (out_mappings)+ *out_mappings = std::move (value_mappings);+ return_trace (true);}public:DEFINE_SIZE_ARRAY (2, *this);};+/* One knot of the avar2 offset-compensation function+ * offset(z) = inv_renorm(z) - z, in new intermediate space. */+struct avar2_offset_knot_t+{+ double z;+ double offset;+};++/* Insert a knot keeping the vector sorted by z; first insertion wins on+ * duplicate z. */+static inline void+_avar2_add_knot (hb_vector_t<avar2_offset_knot_t> &knots, double z, double offset)+{+ unsigned i = 0;+ while (i < knots.length && knots.arrayZ[i].z < z) i++;+ if (i < knots.length && knots.arrayZ[i].z == z) return;+ knots.push (avar2_offset_knot_t {0.0, 0.0});+ if (unlikely (knots.in_error ())) return;+ for (unsigned j = knots.length - 1; j > i; j--)+ knots.arrayZ[j] = knots.arrayZ[j - 1];+ knots.arrayZ[i] = avar2_offset_knot_t {z, offset};+}++/* Piecewise-linear evaluation over the sorted knots. Inputs are always+ * within [-1, +1] and anchor knots at -1/0/+1 always exist. */+static inline double+_avar2_eval_offset (const hb_vector_t<avar2_offset_knot_t> &knots, double z)+{+ unsigned len = knots.length;+ for (unsigned i = 0; i < len; i++)+ {+ if (z == knots.arrayZ[i].z) return knots.arrayZ[i].offset;+ if (z < knots.arrayZ[i].z)+ {+ if (!i) return knots.arrayZ[0].offset;+ const auto &before = knots.arrayZ[i - 1];+ const auto &after = knots.arrayZ[i];+ double denom = after.z - before.z;+ return before.offset + (after.offset - before.offset) * (z - before.z) / denom;+ }+ }+ return len ? knots.arrayZ[len - 1].offset : 0.0;+}++/* Piecewise-linear evaluation over instantiated avar v1 mappings, as+ * produced by SegmentMaps::subset (sorted, with -1/0/+1 anchors).+ * Matches SegmentMaps::map_float for such well-formed mappings. */+static inline double+_avar2_map_new_mapping (const hb_vector_t<AxisValueMap> &mappings, double v,+ unsigned from_offset = 0, unsigned to_offset = 1)+{+ unsigned len = mappings.length;+ if (!len) return v;++ for (unsigned i = 0; i < len; i++)+ {+ double from = (double) mappings.arrayZ[i].coords[from_offset].to_float ();+ if (v == from)+ return (double) mappings.arrayZ[i].coords[to_offset].to_float ();+ if (v < from)+ {+ double to = (double) mappings.arrayZ[i].coords[to_offset].to_float ();+ if (!i) return v - from + to;+ double prev_from = (double) mappings.arrayZ[i - 1].coords[from_offset].to_float ();+ double prev_to = (double) mappings.arrayZ[i - 1].coords[to_offset].to_float ();+ double denom = from - prev_from;+ if (denom == 0.0) return prev_to;+ return prev_to + (to - prev_to) * (v - prev_from) / denom;+ }+ }+ return v - (double) mappings.arrayZ[len - 1].coords[from_offset].to_float ()+ + (double) mappings.arrayZ[len - 1].coords[to_offset].to_float ();+}++/* Inverse of _avar2_map_new_mapping: pull an output coordinate back to a+ * preimage input coordinate. For a non-strictly-monotone mapping this picks+ * one preimage, which is fine for its only use (augmenting the error+ * estimator's sample set). */+static inline double+_avar2_unmap_new_mapping (const hb_vector_t<AxisValueMap> &mappings, double v)+{+ return _avar2_map_new_mapping (mappings, v, 1, 0);+}++/* Plain (non-avar) fvar-style normalization of a user value against a+ * user-space (min, default, max) triple. */+static inline double+_avar2_normalize_value (double v, double min, double def, double max)+{+ v = hb_clamp (v, min, max);+ if (v == def) return 0.0;+ if (v < def) return def == min ? 0.0 : (v - def) / (def - min);+ return def == max ? 0.0 : (v - def) / (max - def);+}++/* Inverse of the above: map a normalized value back to user space. */+static inline double+_avar2_denormalize_value (double v, double min, double def, double max)+{+ if (v == 0.0) return def;+ return v < 0.0 ? def + v * (def - min) : def + v * (max - def);+}++/* Estimate the residual offset-compensation error for one restricted axis:+ * the max |old-avar1-final - (new-avar1 + offset)| over the retained user+ * range, in F2Dot14 units. offset(z) is the piecewise-linear function+ * through the knots. The residual is dominated by F2Dot14 requantization of+ * a steep retained avar v1 segment (e.g. a moved default compressing part+ * of the axis into a narrow z band); offset compensation cannot remove it.+ * Used only to pick the better knot set and decide whether to warn.+ *+ * Sampled on a uniform grid augmented with the user-space preimages of+ * every kink of the residual (old/new avar v1 breakpoints and offset(z)+ * knots), so the worst kink cannot fall between uniform samples. The+ * pointwise F2Dot14 rounding makes this an estimate rather than an exact+ * bound, but every piecewise-linear extremum is visited. */+static inline unsigned+_avar2_estimate_offset_error (const SegmentMaps &old_seg,+ const hb_vector_t<AxisValueMap> &new_mapping,+ double old_min, double old_def, double old_max,+ double new_min, double new_def, double new_max,+ const hb_vector_t<avar2_offset_knot_t> &knots)+{+ constexpr unsigned samples = 257;+ hb_vector_t<double> us;+ if (unlikely (!us.alloc (samples + old_seg.as_array ().length ++ new_mapping.length + knots.length)))+ return UINT_MAX; /* estimator only; fail towards "worse" */+ for (unsigned i = 0; i < samples; i++)+ us.push (new_min + (new_max - new_min) * i / (samples - 1));+ for (const auto &_ : old_seg.as_array ())+ us.push (_avar2_denormalize_value ((double) _.coords[0].to_float (),+ old_min, old_def, old_max));+ for (const auto &_ : new_mapping)+ us.push (_avar2_denormalize_value ((double) _.coords[0].to_float (),+ new_min, new_def, new_max));+ for (const auto &knot : knots)+ us.push (_avar2_denormalize_value (+ _avar2_unmap_new_mapping (new_mapping, knot.z),+ new_min, new_def, new_max));+ if (unlikely (us.in_error ())) return UINT_MAX;++ unsigned max_err = 0;+ for (double u : us)+ {+ if (u < new_min || u > new_max) continue;+ double n_old = _avar2_normalize_value (u, old_min, old_def, old_max);+ double old_final = (double) old_seg.map_float ((float) n_old);+ double n_new = _avar2_normalize_value (u, new_min, new_def, new_max);+ double z = _avar2_map_new_mapping (new_mapping, n_new);+ double new_final = z + _avar2_eval_offset (knots, z);+ int err = abs ((int) roundf ((float) (old_final * 16384.0)) -+ (int) roundf ((float) (new_final * 16384.0)));+ if ((unsigned) err > max_err) max_err = err;+ }+ return max_err;+}+struct avar{static constexpr hb_tag_t tableTag = HB_OT_TAG_avar;@@ -400,7 +574,12 @@ struct avarint v = coords[i];uint32_t varidx = varidx_map.map (i);float delta = var_store.get_delta (varidx, coords_2_14.arrayZ, coords_2_14.length, var_store_cache);- v += roundf (delta * 4); // 2.14 -> 16.16+ /* Apply the delta unclamped and clamp only the result to [-1, +1],+ * matching fontTools. Since inputs and results are in [-1, +1],+ * deltas beyond ±2 are equivalent to ±2; clamp to that range only+ * to keep the float->int conversion safe. */+ float d = hb_clamp (delta * 4, -(float) (1<<17), +(float) (1<<17)); // 2.14 -> 16.16+ v += (int) roundf (d);v = hb_clamp (v, -(1<<16), +(1<<16));out.push (v);}@@ -411,25 +590,53 @@ struct avar#endif}+ /* An avar version 2 font is never downgraded to v1: even with a NULL+ * varStore offset (legal; maps like plain v1) the avar2 subsetting path+ * applies, with "no variation" semantics for rows that don't resolve —+ * offset compensation then creates delta rows on demand. */bool has_v2_data () const { return version.major > 1; }+ /* Resolve the avar2 VarStore and VarIdxMap, for the subset planner.+ * Either pointer may be to the Null object (nullable offsets). */+ bool get_v2_store_and_map (const ItemVariationStore **store,+ const DeltaSetIndexMap **varidx_map) const+ {+#ifndef HB_NO_AVAR2+ if (version.major < 2) return false;+ const SegmentMaps *map = &firstAxisSegmentMaps;+ for (unsigned i = 0; i < axisCount; i++)+ map = &StructAfter<SegmentMaps> (*map);+ const auto &v2 = * (const avarV2Tail *) map;+ *store = &(this+v2.varStore);+ *varidx_map = &(this+v2.varIdxMap);+ return true;+#else+ return false;+#endif+ }+// axis normalization is done in 2.14 here// TODO: deprecate this API once fonttools is updated to use 16.16 normalization- bool map_coords_2_14 (float *coords, unsigned int coords_length) const+ bool map_coords_2_14 (float *coords, unsigned int coords_length,+ bool v1_only = false) const{hb_vector_t<int> coords_2_14;- if (!coords_2_14.resize (coords_length)) return false;+ if (!v1_only && !coords_2_14.resize (coords_length)) return false;unsigned int count = hb_min (coords_length, axisCount);const SegmentMaps *map = &firstAxisSegmentMaps;for (unsigned int i = 0; i < count; i++){int v = roundf (map->map_float (coords[i]) * 16384.f);- coords_2_14[i] = v;+ if (!v1_only)+ coords_2_14[i] = v;coords[i] = v / 16384.f;map = &StructAfter<SegmentMaps> (*map);}+ if (v1_only)+ return true;+#ifndef HB_NO_AVAR2if (version.major < 2)return true;@@ -449,8 +656,10 @@ struct avarint v = coords_2_14[i];uint32_t varidx = varidx_map.map (i);float delta = var_store.get_delta (varidx, coords_2_14.arrayZ, coords_2_14.length, var_store_cache);- v += roundf (delta);- v = hb_clamp (v, -(1<<16), +(1<<16));+ /* As above: apply the delta unclamped (±2 covers every useful case)+ * and clamp the result to [-1, +1], matching fontTools. */+ v += (int) hb_clamp (roundf (delta), -(float) (1<<15), +(float) (1<<15));+ v = hb_clamp (v, -(1<<14), +(1<<14));coords[i] = v / 16384.f;}@@ -471,11 +680,17 @@ struct avaravar *out = c->serializer->allocate_min<avar> ();if (unlikely (!out)) return_trace (false);- out->version.major = 1;+ out->version.major = c->plan->has_avar2 ? 2 : 1;out->version.minor = 0;if (!c->serializer->check_assign (out->axisCount, retained_axis_count, HB_SERIALIZE_ERROR_INT_OVERFLOW))return_trace (false);+ /* For avar2, keep the instantiated v1 mappings around; offset+ * compensation needs them to locate the new mappings' kinks. */+ hb_vector_t<hb_vector_t<AxisValueMap>> new_mappings;+ if (c->plan->has_avar2 && !new_mappings.resize (axisCount))+ return_trace (false);+const hb_map_t& axes_index_map = c->plan->axes_index_map;const SegmentMaps *map = &firstAxisSegmentMaps;unsigned count = axisCount;@@ -486,14 +701,495 @@ struct avarhb_tag_t *axis_tag;if (!c->plan->axes_old_index_tag_map.has (i, &axis_tag))return_trace (false);- if (!map->subset (c, *axis_tag))- return_trace (false);++ Triple *axis_location;+ if (c->plan->has_avar2 &&+ c->plan->user_axes_location.has (*axis_tag, &axis_location) &&+ axis_location->is_point ())+ {+ /* Pinned axis in avar2 mode: serialize identity segment map+ * {-1->-1, 0->0, 1->1}. The axis is kept in fvar as hidden,+ * so avar needs a segment map entry for it. */+ auto *identity_map = c->serializer->start_embed<SegmentMaps> ();+ if (unlikely (!c->serializer->extend_min (identity_map)))+ return_trace (false);+ AxisValueMap m;+ m.set_mapping (-1.f, -1.f);+ if (!m.serialize (c->serializer)) return_trace (false);+ m.set_mapping (0.f, 0.f);+ if (!m.serialize (c->serializer)) return_trace (false);+ m.set_mapping (1.f, 1.f);+ if (!m.serialize (c->serializer)) return_trace (false);+ if (!c->serializer->check_assign (identity_map->len, 3u,+ HB_SERIALIZE_ERROR_INT_OVERFLOW))+ return_trace (false);+ }+ else+ {+ /* Restricted or free axis: use standard SegmentMaps::subset() */+ if (!map->subset (c, *axis_tag,+ c->plan->has_avar2 ? &new_mappings[i] : nullptr))+ return_trace (false);+ }}map = &StructAfter<SegmentMaps> (*map);}++ if (c->plan->has_avar2)+ return_trace (_subset_avar2 (c, new_mappings));+return_trace (true);}+ private:+ struct avar2_index_map_plan_t+ {+ bool init (const hb_vector_t<uint32_t> &varidx_mapping,+ const hb_map_t &axes_index_map,+ unsigned axis_count)+ {+ if (!output_map.alloc (axes_index_map.get_population ()))+ return false;++ bool has_no_variation = false;+ unsigned max_outer = 0, max_inner = 0;+ for (unsigned i = 0; i < axis_count; i++)+ {+ if (!axes_index_map.has (i)) continue;+ uint32_t varidx = varidx_mapping[i];+ output_map.push (varidx);+ if (varidx == HB_OT_LAYOUT_NO_VARIATIONS_INDEX)+ {+ has_no_variation = true;+ continue;+ }+ max_outer = hb_max (max_outer, varidx >> 16);+ max_inner = hb_max (max_inner, varidx & 0xFFFF);+ }+ if (output_map.in_error () ||+ output_map.length != axes_index_map.get_population ())+ return false;++ if (has_no_variation)+ {+ width = 4;+ inner_bit_count = 16;+ }+ else+ {+ inner_bit_count = hb_max (1u, hb_bit_storage (max_inner));+ unsigned outer_bit_count = hb_max (1u, hb_bit_storage (max_outer));+ width = hb_clamp ((inner_bit_count + outer_bit_count + 7) / 8, 1u, 4u);+ if (inner_bit_count + outer_bit_count > width * 8)+ inner_bit_count = width * 8 - outer_bit_count;+ }+ return true;+ }++ unsigned get_inner_bit_count () const { return inner_bit_count; }+ unsigned get_width () const { return width; }+ hb_array_t<const uint32_t> get_output_map () const { return output_map.as_array (); }++ unsigned inner_bit_count = 1;+ unsigned width = 1;+ hb_vector_t<uint32_t> output_map;+ };++ bool _subset_avar2 (hb_subset_context_t *c,+ const hb_vector_t<hb_vector_t<AxisValueMap>> &new_mappings) const+ {+#if defined (HB_NO_VAR) || defined (HB_NO_AVAR2)+ /* Not reachable: the plan never sets has_avar2 in these configurations. */+ return false;+#else++ /* 1. Locate original avar2 data, keeping per-axis old segment maps */+ hb_vector_t<const SegmentMaps *> old_seg_maps;+ if (!old_seg_maps.alloc (axisCount)) return false;+ const SegmentMaps *map = &firstAxisSegmentMaps;+ for (unsigned i = 0; i < axisCount; i++)+ {+ old_seg_maps.push (map);+ map = &StructAfter<SegmentMaps> (*map);+ }++ const auto &v2 = * (const avarV2Tail *) map;+ const auto &varidx_map = this+v2.varIdxMap;+ const auto &var_store = this+v2.varStore;++ auto fvar_axes = c->plan->source->table.fvar->get_axes ();++ /* 2. Compute default deltas by evaluating VarStore at old defaults */+ hb_vector_t<int> default_coords;+ if (!default_coords.resize (axisCount)) return false;+ for (unsigned i = 0; i < axisCount; i++)+ {+ hb_tag_t *axis_tag;+ if (c->plan->axes_old_index_tag_map.has (i, &axis_tag) &&+ c->plan->old_intermediates.has (*axis_tag))+ {+ float d_i = (float) c->plan->old_intermediates.get (*axis_tag).middle;+ default_coords[i] = roundf (d_i * 16384.f);+ }+ else+ default_coords[i] = 0;+ }++ auto *store_cache = var_store.create_cache ();+ hb_vector_t<float> default_deltas;+ if (!default_deltas.resize (axisCount)) {+ ItemVariationStore::destroy_cache (store_cache);+ return false;+ }+ for (unsigned i = 0; i < axisCount; i++)+ {+ uint32_t varidx = varidx_map.map (i);+ if (varidx == HB_OT_LAYOUT_NO_VARIATIONS_INDEX)+ default_deltas[i] = 0.f;+ else+ default_deltas[i] = var_store.get_delta (varidx, default_coords.arrayZ,+ default_coords.length, store_cache);+ }+ ItemVariationStore::destroy_cache (store_cache);++ /* 3. Rebase IVS regions */+ item_variations_t item_vars;+ if (!item_vars.create_from_item_varstore (var_store, c->plan->axes_old_index_tag_map))+ return false;+ if (!item_vars.instantiate_tuple_vars (c->plan->old_intermediates,+ c->plan->axes_triple_distances,+ false))+ return false;++ /* 4. Self-contained pinned axes (whose final coordinate is constant over+ * the retained box) were detected at plan time+ * (_compute_avar2_reachable_ranges) and removed from axes_index_map.+ * They are skipped below; their constant contribution is baked into the+ * other variation tables by standard instancing at the plan's+ * axes_location/normalized_coords. */++ /* 5. Build per-axis varIdx mapping (may create new VarDatas).+ * Entries (or the implicit identity mapping) that don't resolve to a+ * real store row behave as "no variation" at runtime; normalize them to+ * NO_VARIATIONS_INDEX so the offset loop creates fresh rows instead of+ * writing into nonexistent ones. This also covers a NULL VarStore+ * (never downgraded: rows are created on demand). */+ hb_vector_t<uint32_t> new_varidx_mapping;+ if (!new_varidx_mapping.resize (axisCount)) return false;+ for (unsigned i = 0; i < axisCount; i++)+ {+ uint32_t varidx = varidx_map.map (i);+ if (varidx != HB_OT_LAYOUT_NO_VARIATIONS_INDEX &&+ !var_store.has_delta_set (varidx))+ varidx = HB_OT_LAYOUT_NO_VARIATIONS_INDEX;+ new_varidx_mapping[i] = varidx;+ }++ /* 5.5. Privatize shared varIdx delta rows before adding offset+ * compensation. avar2's VarIdxMap may map several fvar axes to the SAME+ * IVS delta row. Writing one axis's offset-compensation deltas into a+ * shared row would corrupt every other axis that reads that row. So give+ * each offset-receiving axis whose row is shared its own private copy of+ * the row (identical contents, preserving the rebased deltas), then+ * repoint its varIdx. Sharers keep the clean row; the varstore+ * optimization pass re-merges identical rows afterwards. */+ hb_hashmap_t<uint32_t, unsigned> varidx_ref_count;+ for (unsigned i = 0; i < axisCount; i++)+ {+ if (!c->plan->axes_index_map.has (i)) continue; /* self-contained: dropped */+ uint32_t varidx = new_varidx_mapping[i];+ if (varidx == HB_OT_LAYOUT_NO_VARIATIONS_INDEX) continue;+ unsigned *count;+ if (varidx_ref_count.has (varidx, &count))+ (*count)++;+ else if (!varidx_ref_count.set (varidx, 1))+ return false;+ }+ for (unsigned i = 0; i < axisCount; i++)+ {+ hb_tag_t *axis_tag_ptr;+ if (!c->plan->axes_old_index_tag_map.has (i, &axis_tag_ptr))+ return false;+ /* Only axes that will receive offset compensation (restricted or+ * pinned) can contaminate a shared row. */+ if (!c->plan->axes_index_map.has (i) ||+ !c->plan->user_axes_location.has (*axis_tag_ptr))+ continue;+ uint32_t varidx = new_varidx_mapping[i];+ if (varidx == HB_OT_LAYOUT_NO_VARIATIONS_INDEX)+ continue; /* gets a fresh, private VarData in the offset loop below */+ unsigned *count;+ if (!varidx_ref_count.has (varidx, &count) || *count <= 1)+ continue; /* sole owner: safe to write offsets in place */+ unsigned outer = varidx >> 16;+ unsigned new_inner = item_vars.duplicate_row (outer, varidx & 0xFFFF);+ if (unlikely (new_inner == (unsigned) -1)) return false;+ new_varidx_mapping[i] = (outer << 16) | new_inner;+ (*count)--;+ }++ /* 6. Add offset compensation tuples.+ * Track processed (outer,inner) pairs to avoid adding duplicate biases+ * when multiple axes share the same varIdx. */+ hb_set_t processed_varidxes;+ for (unsigned i = 0; i < axisCount; i++)+ {+ hb_tag_t *axis_tag_ptr;+ if (!c->plan->axes_old_index_tag_map.has (i, &axis_tag_ptr))+ return false;+ hb_tag_t axis_tag = *axis_tag_ptr;++ /* Self-contained pinned axes are removed from fvar/avar; their+ * contribution is baked into the variation tables instead. */+ if (!c->plan->axes_index_map.has (i))+ continue;++ Triple *new_user;+ if (c->plan->user_axes_location.has (axis_tag, &new_user))+ {+ /* This axis is being restricted or pinned */+ Triple *old_int;+ if (!c->plan->old_intermediates.has (axis_tag, &old_int))+ return false;++ float a_i = (float) old_int->minimum;+ float d_i = (float) old_int->middle;+ float b_i = (float) old_int->maximum;++ int d_int = roundf (d_i * 16384.f);++ bool is_pinned = new_user->is_point ();++ uint32_t varidx = new_varidx_mapping[i];+ unsigned outer, inner, item_count;++ if (varidx == HB_OT_LAYOUT_NO_VARIATIONS_INDEX)+ {+ /* No existing avar2 mapping. Create new VarData. */+ outer = item_vars.add_vardata (1);+ inner = 0;+ item_count = 1;+ new_varidx_mapping[i] = (outer << 16) | inner;+ default_deltas[i] = 0.f; /* no prior default delta */+ }+ else+ {+ outer = varidx >> 16;+ inner = varidx & 0xFFFF;+ item_count = item_vars.get_item_count (outer);+ }++ /* Empty-region bias: d_int + round(defaultDelta) */+ int bias = d_int + (int) roundf (default_deltas[i]);+ if (bias != 0)+ {+ hb_hashmap_t<hb_tag_t, Triple> empty_region;+ item_vars.add_tuple (outer, std::move (empty_region),+ inner, bias, item_count);+ }++ if (!is_pinned)+ {+ /* Offset compensation encodes, as avar2 deltas on this axis, the+ * piecewise-linear function offset(z) = inv_renorm(z) - z, where+ * inv_renorm maps a new intermediate coordinate z back to the old+ * intermediate coordinate. It is known at these knots in the new+ * intermediate space:+ * z = -1 -> a_i + 1 (new minimum)+ * z = 0 -> d_i (new default)+ * z = +1 -> b_i - 1 (new maximum)+ */+ hb_vector_t<avar2_offset_knot_t> knots;+ _avar2_add_knot (knots, -1.0, (double) a_i + 1.0);+ _avar2_add_knot (knots, 0.0, (double) d_i);+ _avar2_add_knot (knots, 1.0, (double) b_i - 1.0);++ const hb_vector_t<AxisValueMap> &new_mapping = new_mappings[i];++ float min_f = 0.f, def_f = 0.f, max_f = 0.f;+ if (likely (i < fvar_axes.length))+ fvar_axes[i].get_coordinates (min_f, def_f, max_f);+ double old_min = (double) min_f;+ double old_def = (double) def_f;+ double old_max = (double) max_f;++ /* If the axis default MOVED, inv_renorm also kinks where the OLD+ * default lands in the new space (the old intermediate coordinate+ * crosses 0 there), at+ * z = z_old -> -z_old+ * Omitting that knot (as a plain two-tent encoding would) makes+ * interior coordinates wrong. */+ double z_old = _avar2_normalize_value ((double) old_def,+ new_user->minimum,+ new_user->middle,+ new_user->maximum);+ z_old = _avar2_map_new_mapping (new_mapping, z_old);+ z_old = (double) roundf ((float) (z_old * 16384.0)) / 16384.0;+ if (-1.0 < z_old && z_old < 1.0)+ _avar2_add_knot (knots, z_old, -z_old);++ /* Interior avar v1 breakpoints inside the retained range each put+ * a kink in offset(z). Sampling only {-1, 0, +1, z_old} would+ * linearly interpolate across those kinks. The instantiated+ * mapping keeps exactly the in-range old breakpoints, and the new+ * mapping kinks at each one's output coordinate; add that z with+ * its old intermediate value so offset(z) is reproduced at every+ * kink. */+ hb_vector_t<avar2_offset_knot_t> with_breakpoints (knots);+ for (const auto &m : new_mapping)+ {+ double from = (double) m.coords[0].to_float ();+ if (from == -1.0 || from == 0.0 || from == 1.0)+ continue; /* anchors already seeded */+ double z = (double) m.coords[1].to_float ();+ if (!(-1.0 < z && z < 1.0))+ continue;+ double user = _avar2_denormalize_value (from,+ new_user->minimum,+ new_user->middle,+ new_user->maximum);+ double n_old = _avar2_normalize_value (user, old_min, old_def, old_max);+ double x_old = (double) old_seg_maps[i]->map_float ((float) n_old);+ x_old = (double) roundf ((float) (x_old * 16384.0)) / 16384.0;+ _avar2_add_knot (with_breakpoints, z, x_old - z);+ }++ if (unlikely (knots.in_error () || with_breakpoints.in_error ()))+ return false;++ /* Extra tents cost F2Dot14 rounding, so for a steep segment they+ * can add more quantization noise than the structural error they+ * remove. Keep the interior breakpoints only when they do not+ * increase the estimated residual; this makes the collection a+ * strict (never-worse) improvement over the {-1, 0, +1, z_old}+ * anchors. Warn when even the better choice is not bit-exact (a+ * steep retained segment that cannot be reproduced in F2Dot14). */+ unsigned err = _avar2_estimate_offset_error (*old_seg_maps[i], new_mapping,+ old_min, old_def, old_max,+ new_user->minimum,+ new_user->middle,+ new_user->maximum,+ knots);+ if (with_breakpoints.length != knots.length)+ {+ unsigned err_with = _avar2_estimate_offset_error (*old_seg_maps[i], new_mapping,+ old_min, old_def, old_max,+ new_user->minimum,+ new_user->middle,+ new_user->maximum,+ with_breakpoints);+ if (err_with <= err)+ {+ knots = std::move (with_breakpoints);+ err = err_with;+ }+ }+ if (err > 8)+ DEBUG_MSG (SUBSET, nullptr,+ "avar2 offset compensation is approximate for axis %c%c%c%c: "+ "max residual %u F2Dot14 units",+ HB_UNTAG (axis_tag), err);++ /* Synthesize tents. Adjacent tents evaluate to zero at each+ * other's peaks, so each knot's delta is offset(z) - offset(0);+ * the base value offset(0) = d_i is carried by the empty-region+ * bias above. This reduces to the classic pair of tents+ * (-1,-1,0) / (0,+1,+1) when the default is unchanged and there+ * are no interior knots. */+ for (unsigned k = 0; k < knots.length; k++)+ {+ double z = knots.arrayZ[k].z;+ if (z == 0.0) continue;+ int delta = (int) roundf ((float) ((knots.arrayZ[k].offset - (double) d_i) * 16384.0));+ if (!delta) continue;+ double lower, upper;+ if (z > 0.0)+ {+ lower = knots.arrayZ[k - 1].z;+ upper = k + 1 < knots.length ? knots.arrayZ[k + 1].z : z;+ }+ else+ {+ upper = knots.arrayZ[k + 1].z;+ lower = k > 0 ? knots.arrayZ[k - 1].z : z;+ }+ hb_hashmap_t<hb_tag_t, Triple> region;+ if (unlikely (!region.set (axis_tag, Triple (lower, z, upper))))+ return false;+ item_vars.add_tuple (outer, std::move (region),+ inner, delta, item_count);+ }+ }+ }+ else+ {+ /* Free or private axis — not being restricted.+ * If it has a non-zero default delta, add it back as a bias.+ * Skip if this (outer,inner) was already processed (shared varIdx). */+ uint32_t varidx = new_varidx_mapping[i];+ if (varidx == HB_OT_LAYOUT_NO_VARIATIONS_INDEX)+ continue;++ if (processed_varidxes.has (varidx))+ continue;+ processed_varidxes.add (varidx);++ unsigned outer = varidx >> 16;+ unsigned inner = varidx & 0xFFFF;+ int dd = (int) roundf (default_deltas[i]);+ if (dd != 0)+ {+ unsigned item_count = item_vars.get_item_count (outer);+ hb_hashmap_t<hb_tag_t, Triple> empty_region;+ item_vars.add_tuple (outer, std::move (empty_region),+ inner, dd, item_count);+ }+ }+ }++ /* 7. Finalize: build region list + convert to varstore */+ if (!item_vars.build_region_list ()) return false;+ if (!item_vars.as_item_varstore (true /* optimize */,+ false /* use_no_variation_idx */))+ return false;++ /* 8. Apply varidx_map optimization remapping */+ const auto &opt_varidx_map = item_vars.get_varidx_map ();+ for (unsigned i = 0; i < axisCount; i++)+ {+ uint32_t varidx = new_varidx_mapping[i];+ if (varidx == HB_OT_LAYOUT_NO_VARIATIONS_INDEX)+ continue;+ uint32_t *new_idx;+ if (opt_varidx_map.has (varidx, &new_idx))+ new_varidx_mapping[i] = *new_idx;+ }++ /* 9. Serialize avarV2Tail. Entries cover the retained axes only;+ * self-contained pinned axes are removed from fvar. */+ avar2_index_map_plan_t index_map_plan;+ if (!index_map_plan.init (new_varidx_mapping,+ c->plan->axes_index_map,+ axisCount))+ return false;++ auto *tail = c->serializer->allocate_size<avarV2Tail> (avarV2Tail::static_size);+ if (unlikely (!tail)) return false;+ if (!tail->varIdxMap.serialize_serialize (c->serializer, index_map_plan))+ return false;+ if (!tail->varStore.serialize_serialize (c->serializer,+ item_vars.has_long_word (),+ c->plan->axis_tags,+ item_vars.get_region_list (),+ item_vars.get_vardata_encodings ()))+ return false;++ return true;+#endif+ }++ public:+protected:FixedVersion<>version; /* Version of the avar table* initially set to 0x00010000u */diff --git a/thirdparty/harfbuzz/src/hb-ot-var-common.hh b/thirdparty/harfbuzz/src/hb-ot-var-common.hhindex f8a663b8ae3..6faa8bc5627 100644--- a/thirdparty/harfbuzz/src/hb-ot-var-common.hh+++ b/thirdparty/harfbuzz/src/hb-ot-var-common.hh@@ -47,7 +47,7 @@ struct TupleVariationHeaderif (unlikely ((ti & (TupleIndex::EmbeddedPeakTuple | TupleIndex::IntermediateRegion)))){unsigned count = ((ti & TupleIndex::EmbeddedPeakTuple) != 0) + ((ti & TupleIndex::IntermediateRegion) != 0) * 2;- return min_size + count * axis_count_times_2;+ return hb_unsigned_mul_add_saturate (count, axis_count_times_2, min_size);}return min_size;}@@ -112,9 +112,22 @@ struct TupleVariationHeaderHB_ALWAYS_INLINEdouble calculate_scalar (hb_array_t<const int> coords, unsigned int coord_count,const hb_array_t<const F2DOT14> shared_tuples,- hb_scalar_cache_t *shared_tuple_scalar_cache = nullptr) const+ hb_scalar_cache_t *shared_tuple_scalar_cache = (hb_scalar_cache_t *) &Null(hb_scalar_cache_t)) const{unsigned tuple_index = tupleIndex;+ unsigned int index = tuple_index & TupleIndex::TupleIndexMask;++ /* The gvar shared-tuple cache is clamped to the 12-bit tuple-index range.+ * Only PrivatePointNumbers may accompany a cached shared-tuple index; any+ * other flag sets a bit at or above 0x1000, making this range test fail.+ */+ bool plain_shared_tuple = (tuple_index & ~TupleIndex::PrivatePointNumbers) < shared_tuple_scalar_cache->length;+ if (likely (plain_shared_tuple))+ {+ float scalar;+ if (likely (shared_tuple_scalar_cache->get (index, &scalar)))+ return (double) scalar;+ }const F2DOT14 *peak_tuple;@@ -127,10 +140,9 @@ struct TupleVariationHeader}else{- unsigned int index = tuple_index & TupleIndex::TupleIndexMask; // Inlined for performance-float scalar;- if (shared_tuple_scalar_cache &&+ if (!plain_shared_tuple &&+ shared_tuple_scalar_cache->length &&shared_tuple_scalar_cache->get (index, &scalar)){if (has_interm && (scalar != 0 && scalar != 1.f))@@ -201,7 +213,7 @@ struct TupleVariationHeaderscalar *= (double) v / peak;}if (shared_tuple_scalar_cache)- shared_tuple_scalar_cache->set (get_index (), scalar);+ shared_tuple_scalar_cache->set (index, scalar);return scalar;}@@ -209,6 +221,7 @@ struct TupleVariationHeaderbool has_intermediate () const { return tupleIndex & TupleIndex::IntermediateRegion; }bool has_private_points () const { return tupleIndex & TupleIndex::PrivatePointNumbers; }unsigned get_index () const { return tupleIndex & TupleIndex::TupleIndexMask; }+ static constexpr unsigned max_shared_tuple_count = 0x1000u;protected:struct TupleIndex : HBUINT16@@ -604,7 +617,7 @@ struct tuple_delta_tfor (unsigned i = 0; i < point_indices.length; i++){if (!point_indices[i]) continue;- rounded_deltas.arrayZ[j++] = (int) roundf (x_deltas.arrayZ[i]);+ rounded_deltas.arrayZ[j++] = hb_clamp_to<int> (roundf ((double) x_deltas.arrayZ[i]));}rounded_deltas.resize (j);@@ -629,7 +642,7 @@ struct tuple_delta_tfor (unsigned idx = 0; idx < point_indices.length; idx++){if (!point_indices[idx]) continue;- int rounded_delta = (int) roundf (y_deltas.arrayZ[idx]);+ int rounded_delta = hb_clamp_to<int> (roundf ((double) y_deltas.arrayZ[idx]));if (j >= rounded_deltas.length) return false;@@ -763,8 +776,8 @@ struct tuple_delta_tfor (unsigned i = 0; i < count; i++){- rounded_x_deltas.arrayZ[i] = (int) roundf (deltas_x.arrayZ[i]);- rounded_y_deltas.arrayZ[i] = (int) roundf (deltas_y.arrayZ[i]);+ rounded_x_deltas.arrayZ[i] = hb_clamp_to<int> (roundf ((double) deltas_x.arrayZ[i]));+ rounded_y_deltas.arrayZ[i] = hb_clamp_to<int> (roundf ((double) deltas_y.arrayZ[i]));}if (!iup_delta_optimize (contour_points, rounded_x_deltas, rounded_y_deltas, opt_indices, scratch.iup, tolerance))@@ -936,12 +949,14 @@ struct TupleVariationDatasize_t get_size (unsigned axis_count_times_2) const{- unsigned total_size = min_size;+ size_t total_size = min_size;unsigned count = tupleVarCount.get_count ();const TupleVariationHeader *tuple_var_header = &(get_tuple_var_header());for (unsigned i = 0; i < count; i++){- total_size += tuple_var_header->get_size (axis_count_times_2) + tuple_var_header->get_data_size ();+ total_size = hb_unsigned_add_saturate (total_size,+ tuple_var_header->get_size (axis_count_times_2),+ (size_t) tuple_var_header->get_data_size ());tuple_var_header = &tuple_var_header->get_next (axis_count_times_2);}@@ -1290,6 +1305,22 @@ struct TupleVariationData}public:+ /* avar2 partial-instancing culling: drop tuples whose region a partial+ * instance can never reach (hb_subset_plan_t::avar2_reachable_ranges). */+ void cull_unreachable (const hb_hashmap_t<hb_tag_t, Triple> &reachable_ranges)+ {+ unsigned j = 0;+ for (unsigned i = 0; i < tuple_vars.length; i++)+ {+ if (_hb_avar2_region_is_dead (tuple_vars.arrayZ[i].axis_tuples, reachable_ranges))+ continue;+ if (i != j)+ tuple_vars.arrayZ[j] = std::move (tuple_vars.arrayZ[i]);+ j++;+ }+ tuple_vars.shrink (j);+ }+bool instantiate (const hb_hashmap_t<hb_tag_t, Triple>& normalized_axes_location,const hb_hashmap_t<hb_tag_t, TripleDistances>& axes_triple_distances,optimize_scratch_t &scratch,@@ -1511,6 +1542,105 @@ struct TupleVariationDatabool has_shared_point_numbers () const { return tupleVarCount.has_shared_point_numbers (); }+ /* avar2 partial-instancing culling: rewrite this tuple variation data,+ * dropping TupleVariations whose region a partial instance can never+ * reach (see hb_subset_plan_t::avar2_reachable_ranges). On success with+ * *changed set, out contains the rewritten data — possibly empty, when+ * every tuple died. Keeps the original data (*changed stays false) when+ * nothing is culled or the data is malformed. Returns false only on+ * allocation failure. */+ bool cull_tuple_variations (hb_bytes_t var_data_bytes,+ unsigned axis_count,+ hb_array_t<const F2DOT14> shared_tuples,+ const hb_map_t *axes_old_index_tag_map,+ const hb_hashmap_t<hb_tag_t, Triple> &reachable_ranges,+ hb_vector_t<char> &out /* OUT */,+ bool *changed /* OUT */) const+ {+ *changed = false;++ hb_vector_t<unsigned int> shared_indices;+ tuple_iterator_t iterator;+ if (!get_tuple_iterator (var_data_bytes, axis_count, this,+ shared_indices, &iterator))+ return true; /* no tuples or malformed: keep original */++ const char *bytes_start = var_data_bytes.arrayZ;+ const char *bytes_end = bytes_start + var_data_bytes.length;+ const char *serialized_base = (const char *) &(this+data);+ const char *shared_points_end = (const char *) iterator.get_serialized_data ();+ if (unlikely (serialized_base < bytes_start || serialized_base > bytes_end ||+ shared_points_end < serialized_base || shared_points_end > bytes_end))+ return true;++ struct kept_tuple_t+ {+ const char *header;+ unsigned header_size;+ const char *data;+ unsigned data_size;+ };+ hb_vector_t<kept_tuple_t> kept;+ unsigned total = 0;+ unsigned kept_headers_size = 0, kept_data_size = 0;+ do+ {+ const TupleVariationHeader *header = iterator.current_tuple;+ unsigned header_size = header->get_size (axis_count * 2);+ unsigned data_size = header->get_data_size ();+ const char *tuple_data = (const char *) iterator.get_serialized_data ();+ if (unlikely (tuple_data < serialized_base ||+ data_size > (unsigned) (bytes_end - tuple_data)))+ return true; /* malformed: keep original */++ hb_hashmap_t<hb_tag_t, Triple> axis_tuples;+ if (!header->unpack_axis_tuples (axis_count, shared_tuples,+ axes_old_index_tag_map, axis_tuples))+ return true;++ total++;+ if (!_hb_avar2_region_is_dead (axis_tuples, reachable_ranges))+ {+ kept.push (kept_tuple_t {(const char *) header, header_size,+ tuple_data, data_size});+ kept_headers_size += header_size;+ kept_data_size += data_size;+ }+ } while (iterator.move_to_next ());++ if (unlikely (kept.in_error ())) return false;+ if (kept.length == total) return true; /* nothing to cull */++ *changed = true;+ if (!kept.length) return true; /* everything culled: no variation data */++ unsigned shared_points_size = shared_points_end - serialized_base;+ unsigned data_offset = min_size + kept_headers_size;+ unsigned new_size = data_offset + shared_points_size + kept_data_size;+ if (unlikely (!out.resize (new_size)))+ return false;++ TupleVariationData *out_data = (TupleVariationData *) out.arrayZ;+ out_data->tupleVarCount = (uint16_t) (kept.length |+ (has_shared_point_numbers () ? 0x8000u : 0u));+ out_data->data = data_offset;++ char *p = out.arrayZ + min_size;+ for (const auto &t : kept)+ {+ hb_memcpy (p, t.header, t.header_size);+ p += t.header_size;+ }+ hb_memcpy (p, serialized_base, shared_points_size);+ p += shared_points_size;+ for (const auto &t : kept)+ {+ hb_memcpy (p, t.data, t.data_size);+ p += t.data_size;+ }+ return true;+ }+static bool decompile_points (const HBUINT8 *&p /* IN/OUT */,hb_vector_t<unsigned int> &points /* OUT */,const HBUINT8 *end)@@ -1725,6 +1855,10 @@ struct item_variations_t{if (!create_from_item_varstore (varStore, plan->axes_old_index_tag_map, inner_maps))return false;+ /* avar2 partial instancing: cull unreachable regions. */+ if (plan->has_avar2 && plan->avar2_reachable_ranges.get_population ())+ for (tuple_variations_t& tuple_vars : vars)+ tuple_vars.cull_unreachable (plan->avar2_reachable_ranges);if (!instantiate_tuple_vars (plan->axes_location, plan->axes_triple_distances))return false;return as_item_varstore (optimize, use_no_variation_idx);@@ -1764,15 +1898,75 @@ struct item_variations_t}bool instantiate_tuple_vars (const hb_hashmap_t<hb_tag_t, Triple>& normalized_axes_location,- const hb_hashmap_t<hb_tag_t, TripleDistances>& axes_triple_distances)+ const hb_hashmap_t<hb_tag_t, TripleDistances>& axes_triple_distances,+ bool build_regions = true){optimize_scratch_t scratch;for (tuple_variations_t& tuple_vars : vars)if (!tuple_vars.instantiate (normalized_axes_location, axes_triple_distances, scratch))return false;- if (!build_region_list ()) return false;- return true;+ return !build_regions || build_region_list ();+ }++ /* Add a new VarData subtable. Returns outer index. */+ unsigned add_vardata (unsigned item_count)+ {+ vars.push (tuple_variations_t ());+ var_data_num_rows.push (item_count);+ return vars.length - 1;+ }++ /* Get item count for a VarData subtable. */+ unsigned get_item_count (unsigned outer) const+ { return outer < var_data_num_rows.length ? var_data_num_rows[outer] : 0; }++ /* Duplicate the delta row at position inner within VarData subtable outer,+ * appending the copy as a new item. Used to give an axis a private copy of+ * a delta row that avar2's VarIdxMap shares between several axes, before+ * per-axis offset-compensation deltas are written into it. Returns the new+ * inner index, or (unsigned) -1 on failure. */+ unsigned duplicate_row (unsigned outer, unsigned inner)+ {+ if (unlikely (outer >= vars.length ||+ inner >= var_data_num_rows[outer] ||+ var_data_num_rows[outer] >= 0xFFFFu))+ return (unsigned) -1;+ for (tuple_delta_t& tuple : vars[outer].tuple_vars)+ {+ if (unlikely (inner >= tuple.deltas_x.length ||+ inner >= tuple.indices.length))+ return (unsigned) -1;+ tuple.indices.push (tuple.indices.arrayZ[inner]);+ tuple.deltas_x.push (tuple.deltas_x.arrayZ[inner]);+ if (inner < tuple.deltas_y.length)+ tuple.deltas_y.push (tuple.deltas_y.arrayZ[inner]);+ if (unlikely (tuple.indices.in_error () ||+ tuple.deltas_x.in_error () ||+ tuple.deltas_y.in_error ()))+ return (unsigned) -1;+ }+ return var_data_num_rows[outer]++;+ }++ /* Add a tuple with a single non-zero delta at position inner.+ * axis_tuples defines the region (empty map = constant/bias tuple). */+ void add_tuple (unsigned outer,+ hb_hashmap_t<hb_tag_t, Triple>&& axis_tuples,+ unsigned inner, int delta, unsigned item_count)+ {+ if (outer >= vars.length) return;+ tuple_delta_t tuple;+ tuple.axis_tuples = std::move (axis_tuples);+ if (!tuple.indices.resize (item_count) ||+ !tuple.deltas_x.resize (item_count)) return;+ for (unsigned i = 0; i < item_count; i++)+ {+ tuple.indices.arrayZ[i] = true;+ tuple.deltas_x.arrayZ[i] = 0.f;+ }+ tuple.deltas_x[inner] = (float) delta;+ vars[outer].tuple_vars.push (std::move (tuple));}bool build_region_list ()@@ -1793,7 +1987,7 @@ struct item_variations_tbool all_zeros = true;for (float d : tuple.deltas_x){- int delta = (int) roundf (d);+ int delta = hb_clamp_to<int> (roundf ((double) d));if (delta != 0){all_zeros = false;@@ -1921,7 +2115,7 @@ struct item_variations_tfor (unsigned i = 0; i < num_rows; i++){- int rounded_delta = roundf (tuple.deltas_x[i]);+ int rounded_delta = hb_clamp_to<int> (roundf ((double) tuple.deltas_x[i]));delta_rows[start_row + i][*col_idx] += rounded_delta;has_long |= rounded_delta < -65536 || rounded_delta > 65535;}@@ -1949,10 +2143,16 @@ struct item_variations_tif (!front_mapping.set ((major<<16) + minor, &row))return false;- if (delta_rows_map.has (&row))- continue;+ /* Duplicate rows may only be dropped when optimizing: without a+ * varidx_map the caller relies on original VariationIndex values+ * staying valid (e.g. HVAR/VVAR with an implicit advance mapping). */+ if (optimize)+ {+ if (delta_rows_map.has (&row))+ continue;- delta_rows_map.set (&row, 1);+ delta_rows_map.set (&row, 1);+ }major_rows.push (&row);}diff --git a/thirdparty/harfbuzz/src/hb-ot-var-cvar-table.hh b/thirdparty/harfbuzz/src/hb-ot-var-cvar-table.hhindex 358a95539f0..1e7532bcaf8 100644--- a/thirdparty/harfbuzz/src/hb-ot-var-cvar-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-var-cvar-table.hh@@ -79,12 +79,12 @@ struct cvarunsigned num_cvt_item,const TupleVariationData<> *tuple_var_data,const void *base,+ unsigned var_data_length,hb_vector_t<float>& cvt_deltas /* OUT */){if (!coords) return true;hb_vector_t<unsigned> shared_indices;TupleVariationData<>::tuple_iterator_t iterator;- unsigned var_data_length = tuple_var_data->get_size (axis_count * 2);hb_bytes_t var_data_bytes = hb_bytes_t (reinterpret_cast<const char*> (tuple_var_data), var_data_length);if (!TupleVariationData<>::get_tuple_iterator (var_data_bytes, axis_count, base,shared_indices, &iterator))@@ -191,8 +191,17 @@ struct cvarreturn false;}+ /* Bound the tuple variation data by the actual cvar table length rather+ * than trusting tupleVarCount to walk the headers; an inflated count would+ * otherwise run get_size() off the end of the table. */+ hb_blob_t *cvar_blob = hb_face_reference_table (plan->source, cvar::tableTag);+ unsigned cvar_length = hb_blob_get_length (cvar_blob);+ hb_blob_destroy (cvar_blob);+ unsigned var_data_offset = (unsigned) ((const char *) tuple_var_data - (const char *) base);+ unsigned var_data_length = var_data_offset < cvar_length ? cvar_length - var_data_offset : 0;+if (!calculate_cvt_deltas (plan->normalized_coords.length, plan->normalized_coords.as_array (),- num_cvt_item, tuple_var_data, base, cvt_deltas))+ num_cvt_item, tuple_var_data, base, var_data_length, cvt_deltas)){hb_blob_destroy (cvt_prime_blob);return false;diff --git a/thirdparty/harfbuzz/src/hb-ot-var-fvar-table.hh b/thirdparty/harfbuzz/src/hb-ot-var-fvar-table.hhindex 4b4410f9ba1..142055c29a3 100644--- a/thirdparty/harfbuzz/src/hb-ot-var-fvar-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-var-fvar-table.hh@@ -107,8 +107,9 @@ struct InstanceRecordif (!axis_coord_pinned_or_within_axis_range (coords, i, *axis_limit))return_trace (false);- //skip pinned axis- if (axis_limit->is_point ())+ //skip axes dropped from fvar (pinned; or self-contained under avar2,+ //where other pinned axes stay in fvar as hidden)+ if (axis_limit->is_point () && !c->plan->axes_index_map.has (i))continue;}@@ -179,6 +180,8 @@ struct AxisRecordhb_tag_t get_axis_tag () const { return axisTag; }+ bool is_hidden () const { return flags & AXIS_FLAG_HIDDEN; }+float normalize_axis_value (float v) const{float min_value, default_value, max_value;@@ -235,9 +238,21 @@ struct AxisRecordTriple *axis_limit;if (user_axes_location.has (axisTag, &axis_limit)){- out->minValue.set_float (axis_limit->minimum);- out->defaultValue.set_float (axis_limit->middle);- out->maxValue.set_float (axis_limit->maximum);+ if (c->plan->has_avar2 && axis_limit->is_point ())+ {+ /* Pinned axis in avar2 mode: keep in fvar as hidden with+ * min=default=max=pinned_value. */+ out->minValue.set_float (axis_limit->middle);+ out->defaultValue.set_float (axis_limit->middle);+ out->maxValue.set_float (axis_limit->middle);+ out->flags = out->flags | (HBUINT16) AXIS_FLAG_HIDDEN;+ }+ else+ {+ out->minValue.set_float (axis_limit->minimum);+ out->defaultValue.set_float (axis_limit->middle);+ out->maxValue.set_float (axis_limit->maximum);+ }}return_trace (true);}@@ -285,7 +300,7 @@ struct fvarunsigned int *axes_count /* IN/OUT */,hb_ot_var_axis_t *axes_array /* OUT */) const{- if (axes_count)+ if (axes_count && axes_array){hb_array_t<const AxisRecord> arr = get_axes ().sub_array (start_offset, axes_count);for (unsigned i = 0; i < arr.length; ++i)@@ -299,7 +314,7 @@ struct fvarunsigned int *axes_count /* IN/OUT */,hb_ot_var_axis_info_t *axes_array /* OUT */) const{- if (axes_count)+ if (axes_count && axes_array){hb_array_t<const AxisRecord> arr = get_axes ().sub_array (start_offset, axes_count);for (unsigned i = 0; i < arr.length; ++i)@@ -360,7 +375,7 @@ struct fvarreturn 0;}- if (coords_length && *coords_length)+ if (coords_length && *coords_length && coords){hb_array_t<const F16DOT16> instanceCoords = instance->get_coordinates (axisCount).sub_array (0, coords_length);diff --git a/thirdparty/harfbuzz/src/hb-ot-var-gvar-table.hh b/thirdparty/harfbuzz/src/hb-ot-var-gvar-table.hhindex 349d6e28746..ec1de51df68 100644--- a/thirdparty/harfbuzz/src/hb-ot-var-gvar-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-var-gvar-table.hh@@ -150,6 +150,9 @@ struct glyph_variations_tcontour_point_vector_t *all_points;if (!plan->new_gid_contour_points_map.has (new_gid, &all_points))return false;+ /* avar2 partial instancing: cull unreachable tuples. */+ if (plan->has_avar2 && plan->avar2_reachable_ranges.get_population ())+ glyph_variations[i].cull_unreachable (plan->avar2_reachable_ranges);if (!glyph_variations[i].instantiate (plan->axes_location, plan->axes_triple_distances, scratch, &pool, all_points, iup_optimize))return false;}@@ -444,22 +447,55 @@ struct gvar_GVARunsigned int num_glyphs = c->plan->num_output_glyphs ();out->glyphCountX = hb_min (0xFFFFu, num_glyphs);+ /* avar2 partial instancing: cull tuple variations whose region falls+ * outside the reachable old-space final-coord ranges. Rewritten glyph+ * data is cached per new gid; untouched glyphs are copied verbatim. */+ hb_vector_t<hb_vector_t<char>> culled_vars;+ hb_set_t culled_gids;+ if (c->plan->has_avar2 && c->plan->avar2_reachable_ranges.get_population ())+ {+ hb_array_t<const F2DOT14> shared_tuples_array =+ (this+sharedTuples).as_array ((unsigned) sharedTupleCount * (unsigned) axisCount);+ if (unlikely (!culled_vars.resize (num_glyphs))) return_trace (false);+ auto cull_it = hb_iter (c->plan->new_to_old_gid_list);+ if (cull_it->first == 0 && !(c->plan->flags & HB_SUBSET_FLAGS_NOTDEF_OUTLINE))+ cull_it++;+ for (auto &_ : cull_it)+ {+ hb_bytes_t var_data_bytes = get_glyph_var_data_bytes (c->source_blob, glyph_count, _.second);+ if (var_data_bytes.length < GlyphVariationData::min_size) continue;+ bool changed = false;+ if (unlikely (!var_data_bytes.as<GlyphVariationData> ()+ ->cull_tuple_variations (var_data_bytes, axisCount,+ shared_tuples_array,+ &c->plan->axes_old_index_tag_map,+ c->plan->avar2_reachable_ranges,+ culled_vars[_.first], &changed)))+ return_trace (false);+ if (changed) culled_gids.add (_.first);+ }+ if (unlikely (culled_gids.in_error ())) return_trace (false);+ }+auto it = hb_iter (c->plan->new_to_old_gid_list);if (it->first == 0 && !(c->plan->flags & HB_SUBSET_FLAGS_NOTDEF_OUTLINE))it++;- size_t subset_data_size = 0;+ unsigned subset_data_size = 0;unsigned padding_size = 0;for (auto &_ : it){hb_codepoint_t old_gid = _.second;- unsigned glyph_data_size = get_glyph_var_data_bytes (c->source_blob, glyph_count, old_gid).length;+ unsigned glyph_data_size = culled_gids.has (_.first)+ ? culled_vars[_.first].length+ : get_glyph_var_data_bytes (c->source_blob, glyph_count, old_gid).length;if (glyph_data_size % 2){glyph_data_size++;padding_size++;}- subset_data_size += glyph_data_size;+ if (unlikely (hb_unsigned_add_overflows (subset_data_size, glyph_data_size, &subset_data_size)))+ return_trace (false);}/* According to the spec: If the short format (Offset16) is used for offsets,@@ -523,9 +559,12 @@ struct gvar_GVARfor (; last < gid; last++)((HBUINT16 *) subset_offsets)[last] = glyph_offset / 2;- hb_bytes_t var_data_bytes = get_glyph_var_data_bytes (c->source_blob,- glyph_count,- old_gid);+ hb_bytes_t var_data_bytes = culled_gids.has (gid)+ ? hb_bytes_t (culled_vars[gid].arrayZ,+ culled_vars[gid].length)+ : get_glyph_var_data_bytes (c->source_blob,+ glyph_count,+ old_gid);hb_memcpy (subset_data, var_data_bytes.arrayZ, var_data_bytes.length);unsigned glyph_data_size = var_data_bytes.length;@@ -588,7 +627,8 @@ struct gvar_GVARhb_scalar_cache_t *create_cache () const{- return hb_scalar_cache_t::create (table->sharedTupleCount);+ return hb_scalar_cache_t::create (hb_min ((unsigned) table->sharedTupleCount,+ +TupleVariationHeader::max_shared_tuple_count));}static void destroy_cache (hb_scalar_cache_t *cache)@@ -720,6 +760,9 @@ struct gvar_GVARbool phantom_only = false) const{if (unlikely (glyph >= glyphCount)) return true;+ hb_scalar_cache_t *scalar_cache = gvar_cache ?+ gvar_cache :+ (hb_scalar_cache_t *) &Null(hb_scalar_cache_t);hb_bytes_t var_data_bytes = table->get_glyph_var_data_bytes (table.get_blob (), glyphCount, glyph);if (!var_data_bytes.as<GlyphVariationData> ()->has_data ()) return true;@@ -759,7 +802,7 @@ struct gvar_GVARdo{float scalar = iterator.current_tuple->calculate_scalar (coords, num_coords, shared_tuples,- gvar_cache);+ scalar_cache);if (scalar == 0.f) continue;diff --git a/thirdparty/harfbuzz/src/hb-ot-var-hvar-table.hh b/thirdparty/harfbuzz/src/hb-ot-var-hvar-table.hhindex 14ccdb7660f..58fcea2504c 100644--- a/thirdparty/harfbuzz/src/hb-ot-var-hvar-table.hh+++ b/thirdparty/harfbuzz/src/hb-ot-var-hvar-table.hh@@ -49,6 +49,12 @@ struct index_map_subset_plan_tbool bypass_empty = true){map_count = 0;+ full_map_count = plan->new_to_old_gid_list.length ?+ plan->new_to_old_gid_list.tail ().first + 1 : 0;+ /* Only the advance mapping may be dropped in favor of implicit+ * glyph-id indexing (for the others a null offset means no deltas),+ * and only when the source was map-less too, preserving its form. */+ can_drop_to_implicit = !bypass_empty && !index_map;max_inners.init ();output_map.init ();@@ -181,13 +187,30 @@ struct index_map_subset_plan_tunsigned int get_map_count () const { return map_count; }size_t get_size () const- { return (map_count? (DeltaSetIndexMap::min_size + get_width () * map_count): 0); }+ {+ if (!map_count) return 0;+ return hb_unsigned_mul_add_saturate (get_width (), map_count,+ DeltaSetIndexMap::min_size);+ }- bool is_identity () const { return get_output_map ().length == 0; }+ bool is_identity () const+ {+ if (!output_map) return true;+ /* An advance map whose entries are the identity over every output+ * glyph is equivalent to implicit glyph-id indexing; drop it. A+ * truncated map doesn't qualify: glyphs past its end share its last+ * value, not their own ids. */+ if (!can_drop_to_implicit || map_count != full_map_count) return false;+ for (unsigned i = 0; i < map_count; i++)+ if (output_map.arrayZ[i] != i) return false;+ return true;+ }hb_array_t<const uint32_t> get_output_map () const { return output_map.as_array (); }protected:unsigned int map_count;+ unsigned int full_map_count;+ bool can_drop_to_implicit;hb_vector_t<unsigned int> max_inners;unsigned int outer_bit_count;unsigned int inner_bit_count;@@ -390,10 +413,18 @@ struct HVARVVAR}else{+ /* avar2 partial instancing: cull unreachable regions. */+ hb_set_t dead_regions;+ if (c->plan->has_avar2)+ hvar_plan.var_store->collect_dead_regions (c->plan->axes_old_index_tag_map,+ c->plan->avar2_reachable_ranges,+ dead_regions);+if (unlikely (!out->varStore.serialize_serialize (c->serializer,hvar_plan.var_store,- hvar_plan.inner_maps.as_array ())))+ hvar_plan.inner_maps.as_array (),+ dead_regions.get_population () ? &dead_regions : nullptr)))return_trace (false);}diff --git a/thirdparty/harfbuzz/src/hb-ot-var.cc b/thirdparty/harfbuzz/src/hb-ot-var.ccindex 72ef9fbbd9d..5c2016fe479 100644--- a/thirdparty/harfbuzz/src/hb-ot-var.cc+++ b/thirdparty/harfbuzz/src/hb-ot-var.cc@@ -89,7 +89,7 @@ hb_ot_var_get_axis_count (hb_face_t *face)* @start_offset: offset of the first lookup to retrieve* @axes_count: (inout) (optional): Input = the maximum number of variation axes to return;* Output = the actual number of variation axes returned (may be zero)- * @axes_array: (out caller-allocates) (array length=axes_count): The array of variation axes found+ * @axes_array: (out caller-allocates) (array length=axes_count) (nullable): The array of variation axes found** Fetches a list of all variation axes in the specified face. The list returned will begin* at the offset provided.@@ -135,7 +135,7 @@ hb_ot_var_find_axis (hb_face_t *face,* @start_offset: offset of the first lookup to retrieve* @axes_count: (inout) (optional): Input = the maximum number of variation axes to return;* Output = the actual number of variation axes returned (may be zero)- * @axes_array: (out caller-allocates) (array length=axes_count): The array of variation axes found+ * @axes_array: (out caller-allocates) (array length=axes_count) (nullable): The array of variation axes found** Fetches a list of all variation axes in the specified face. The list returned will begin* at the offset provided.@@ -239,7 +239,7 @@ hb_ot_var_named_instance_get_postscript_name_id (hb_face_t *face,* @instance_index: The index of the named instance to query* @coords_length: (inout) (optional): Input = the maximum number of coordinates to return;* Output = the actual number of coordinates returned (may be zero)- * @coords: (out) (array length=coords_length): The array of coordinates found for the query+ * @coords: (out) (array length=coords_length) (nullable): The array of coordinates found for the query** Fetches the design-space coordinates corresponding to the given* named instance in the face.diff --git a/thirdparty/harfbuzz/src/hb-ot.h b/thirdparty/harfbuzz/src/hb-ot.hindex f2dbaa1b317..f0d3521a893 100644--- a/thirdparty/harfbuzz/src/hb-ot.h+++ b/thirdparty/harfbuzz/src/hb-ot.h@@ -30,6 +30,7 @@#include "hb.h"+#include "hb-ot-fetch.h"#include "hb-ot-color.h"#include "hb-ot-deprecated.h"#include "hb-ot-font.h"diff --git a/thirdparty/harfbuzz/src/hb-paint-extents.cc b/thirdparty/harfbuzz/src/hb-paint-extents.ccindex 11339a76a05..7244612c777 100644--- a/thirdparty/harfbuzz/src/hb-paint-extents.cc+++ b/thirdparty/harfbuzz/src/hb-paint-extents.cc@@ -62,6 +62,92 @@ hb_paint_extents_pop_transform (hb_paint_funcs_t *funcs HB_UNUSED,c->pop_transform ();}+/* Like the hb_draw_extents_get_funcs() sink, but also counts the+ * consumed segments so they can be charged against the session work+ * budget. */+struct hb_paint_extents_counting_sink_t+{+ hb_extents_t<> extents;+ int64_t count = 0;+};++static void+hb_paint_extents_count_move_to (hb_draw_funcs_t *dfuncs HB_UNUSED, void *data,+ hb_draw_state_t *st HB_UNUSED,+ float to_x, float to_y,+ void *user_data HB_UNUSED)+{+ hb_paint_extents_counting_sink_t *sink = (hb_paint_extents_counting_sink_t *) data;+ sink->count++;+ sink->extents.add_point (to_x, to_y);+}++static void+hb_paint_extents_count_line_to (hb_draw_funcs_t *dfuncs HB_UNUSED, void *data,+ hb_draw_state_t *st HB_UNUSED,+ float to_x, float to_y,+ void *user_data HB_UNUSED)+{+ hb_paint_extents_counting_sink_t *sink = (hb_paint_extents_counting_sink_t *) data;+ sink->count++;+ sink->extents.add_point (to_x, to_y);+}++static void+hb_paint_extents_count_quadratic_to (hb_draw_funcs_t *dfuncs HB_UNUSED, void *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_paint_extents_counting_sink_t *sink = (hb_paint_extents_counting_sink_t *) data;+ sink->count++;+ sink->extents.add_point (control_x, control_y);+ sink->extents.add_point (to_x, to_y);+}++static void+hb_paint_extents_count_cubic_to (hb_draw_funcs_t *dfuncs HB_UNUSED, void *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_paint_extents_counting_sink_t *sink = (hb_paint_extents_counting_sink_t *) data;+ sink->count++;+ sink->extents.add_point (control1_x, control1_y);+ sink->extents.add_point (control2_x, control2_y);+ sink->extents.add_point (to_x, to_y);+}++static inline void free_static_paint_extents_draw_funcs ();++static struct hb_paint_extents_draw_funcs_lazy_loader_t : hb_draw_funcs_lazy_loader_t<hb_paint_extents_draw_funcs_lazy_loader_t>+{+ static hb_draw_funcs_t *create ()+ {+ hb_draw_funcs_t *funcs = hb_draw_funcs_create ();++ hb_draw_funcs_set_move_to_func (funcs, hb_paint_extents_count_move_to, nullptr, nullptr);+ hb_draw_funcs_set_line_to_func (funcs, hb_paint_extents_count_line_to, nullptr, nullptr);+ hb_draw_funcs_set_quadratic_to_func (funcs, hb_paint_extents_count_quadratic_to, nullptr, nullptr);+ hb_draw_funcs_set_cubic_to_func (funcs, hb_paint_extents_count_cubic_to, nullptr, nullptr);++ hb_draw_funcs_make_immutable (funcs);++ hb_atexit (free_static_paint_extents_draw_funcs);++ return funcs;+ }+} static_paint_extents_draw_funcs;++static inline+void free_static_paint_extents_draw_funcs ()+{+ static_paint_extents_draw_funcs.free_instance ();+}+static voidhb_paint_extents_push_clip_glyph (hb_paint_funcs_t *funcs HB_UNUSED,void *paint_data,@@ -71,10 +157,15 @@ hb_paint_extents_push_clip_glyph (hb_paint_funcs_t *funcs HB_UNUSED,{hb_paint_extents_context_t *c = (hb_paint_extents_context_t *) paint_data;- hb_extents_t<> extents;- hb_draw_funcs_t *draw_extent_funcs = hb_draw_extents_get_funcs ();- hb_font_draw_glyph (font, glyph, draw_extent_funcs, &extents);- c->push_clip (extents);+ hb_paint_extents_counting_sink_t sink;+ /* Skip the outline extraction when the session work budget is+ * spent; an empty clip clips everything out. */+ if (likely (c->work_left > 0))+ {+ hb_font_draw_glyph (font, glyph, static_paint_extents_draw_funcs.get_unconst (), &sink);+ c->work_left -= 1 + sink.count;+ }+ c->push_clip (sink.extents);}static voiddiff --git a/thirdparty/harfbuzz/src/hb-paint-extents.hh b/thirdparty/harfbuzz/src/hb-paint-extents.hhindex 0e18e3f8aab..102af2b7ff6 100644--- a/thirdparty/harfbuzz/src/hb-paint-extents.hh+++ b/thirdparty/harfbuzz/src/hb-paint-extents.hh@@ -40,6 +40,7 @@ struct hb_paint_extents_context_ttransforms.clear ();clips.clear ();groups.clear ();+ work_left = HB_PAINT_EXTENTS_MAX_WORK;transforms.push (hb_transform_t<>{});clips.push (hb_bounds_t<>{hb_bounds_t<>::UNBOUNDED});@@ -131,6 +132,12 @@ struct hb_paint_extents_context_tgroup.union_ (clip);}+ /* Cumulative work budget for the current session; reset by clear().+ * Charged with the outline points consumed by each clip-glyph draw,+ * so per-glyph outline limits cannot multiply with the paint-graph+ * traversal limits of the font tables driving us (e.g. COLR). */+ int64_t work_left = HB_PAINT_EXTENTS_MAX_WORK;+protected:hb_vector_t<hb_transform_t<>> transforms;hb_vector_t<hb_bounds_t<>> clips;diff --git a/thirdparty/harfbuzz/src/hb-paint.cc b/thirdparty/harfbuzz/src/hb-paint.ccindex 4565635a70c..08b00accca4 100644--- a/thirdparty/harfbuzz/src/hb-paint.cc+++ b/thirdparty/harfbuzz/src/hb-paint.cc@@ -60,6 +60,20 @@ hb_paint_color_glyph_nil (hb_paint_funcs_t *funcs, void *paint_data,hb_font_t *font,void *user_data) { return false; }+static void+hb_paint_fill_glyph_nil (hb_paint_funcs_t *funcs, void *paint_data,+ hb_codepoint_t glyph,+ hb_font_t *font,+ hb_bool_t is_foreground,+ hb_color_t color,+ void *user_data)+{+ /* Decompose into the equivalent general sequence. */+ funcs->push_clip_glyph (paint_data, glyph, font);+ funcs->color (paint_data, is_foreground, color);+ funcs->pop_clip (paint_data);+}+static voidhb_paint_push_clip_glyph_nil (hb_paint_funcs_t *funcs, void *paint_data,hb_codepoint_t glyph,@@ -551,6 +565,30 @@ hb_paint_color_glyph (hb_paint_funcs_t *funcs, void *paint_data,return funcs->color_glyph (paint_data, glyph, font);}+/**+ * hb_paint_fill_glyph:+ * @funcs: paint functions+ * @paint_data: associated data passed by the caller+ * @glyph: the glyph ID+ * @font: the font+ * @is_foreground: whether the color is the foreground+ * @color: The color to use+ *+ * Perform a "fill-glyph" paint operation: fill the glyph's shape+ * with a solid color.+ *+ * Since: 14.3.0+ */+void+hb_paint_fill_glyph (hb_paint_funcs_t *funcs, void *paint_data,+ hb_codepoint_t glyph,+ hb_font_t *font,+ hb_bool_t is_foreground,+ hb_color_t color)+{+ funcs->fill_glyph (paint_data, glyph, font, is_foreground, color);+}+/*** hb_paint_push_clip_glyph:* @funcs: paint functions@@ -939,7 +977,7 @@ hb_paint_normalize_color_line (hb_color_stop_t *stops,hb_array_t<hb_color_stop_t> (stops, len).qsort ([] (const hb_color_stop_t &a, const hb_color_stop_t &b) {- return a.offset < b.offset;+ return (a.offset > b.offset) - (a.offset < b.offset);});float mn = stops[0].offset, mx = stops[0].offset;@@ -1082,34 +1120,53 @@ hb_paint_sweep_gradient_tiles (hb_color_stop_t *stops,else{float span = angles[n_stops - 1] - angles[0];- if (fabsf (span) < 1e-6f)+ if (!(fabsf (span) >= 1e-6f)) /* Reversed to catch NaN. */goto done;- int k = 0;- if (angles[0] >= 0)- {- float ss = angles[0];- while (ss > 0)- {- if (span > 0) { ss -= span; k--; }- else { ss += span; k++; }- }- }- else+ span = fabsf (span);++ if (span < HB_2_PI / HB_PAINT_MAX_SWEEP_TILES){- float ee = angles[n_stops - 1];- while (ee < 0)+ /* The pattern repeats faster than the tile resolution; tiling+ * it would cost unbounded work for sub-visual detail. Fill+ * the whole circle with the period-average color instead. */+ float r = 0.f, g = 0.f, b = 0.f, a = 0.f;+ for (unsigned i = 1; i < n_stops; i++){- if (span > 0) { ee += span; k++; }- else { ee -= span; k--; }+ float w = (angles[i] - angles[i - 1]) / span * 0.5f;+ r += w * (hb_color_get_red (colors[i - 1]) + hb_color_get_red (colors[i]));+ g += w * (hb_color_get_green (colors[i - 1]) + hb_color_get_green (colors[i]));+ b += w * (hb_color_get_blue (colors[i - 1]) + hb_color_get_blue (colors[i]));+ a += w * (hb_color_get_alpha (colors[i - 1]) + hb_color_get_alpha (colors[i]));}+ hb_color_t avg = HB_COLOR (hb_clamp_to<uint8_t> ((double) b + 0.5),+ hb_clamp_to<uint8_t> ((double) g + 0.5),+ hb_clamp_to<uint8_t> ((double) r + 0.5),+ hb_clamp_to<uint8_t> ((double) a + 0.5));+ emit_patch (0.f, avg, HB_2_PI, avg, user_data);+ goto done;}- span = fabsf (span);- for (int l = k; l < 1000; l++)+ /* First repeat that can reach angle 0, computed by division;+ * counting there one span at a time can take effectively forever,+ * or fail to terminate outright once the span drops below the+ * float ulp of the angles. One repeat of slack absorbs rounding+ * differences; earlier repeats are fully clipped anyway. */+ double dk = floor (-(double) hb_max (angles[0], angles[n_stops - 1]) / (double) span) - 1.;+ if (!(dk >= -1.e18 && dk <= 1.e18)) /* Non-finite angles. */+ goto done;++ unsigned iterations = 0, tiles = 0;+ for (int64_t l = (int64_t) dk; ; l++){for (unsigned i = 1; i < n_stops; i++){+ /* Bounds clipped-away segments too; those stay negligible for+ * sorted stops but are unbounded if the sort contract is+ * violated. */+ if (unlikely (iterations++ >= 256 * HB_PAINT_MAX_SWEEP_TILES))+ goto done;+float a0_l, a1_l;hb_color_t col0, col1;if ((l % 2 != 0) && (extend == HB_PAINT_EXTEND_REFLECT))@@ -1128,6 +1185,8 @@ hb_paint_sweep_gradient_tiles (hb_color_stop_t *stops,}if (a1_l < 0.f) continue;+ if (unlikely (tiles++ >= HB_PAINT_MAX_SWEEP_TILES))+ goto done;if (a0_l < 0.f){float f = (0.f - a0_l) / (a1_l - a0_l);diff --git a/thirdparty/harfbuzz/src/hb-paint.h b/thirdparty/harfbuzz/src/hb-paint.hindex 9057e3b720b..7064b34565a 100644--- a/thirdparty/harfbuzz/src/hb-paint.h+++ b/thirdparty/harfbuzz/src/hb-paint.h@@ -157,6 +157,31 @@ typedef hb_bool_t (*hb_paint_color_glyph_func_t) (hb_paint_funcs_t *funcs,hb_font_t *font,void *user_data);+/**+ * hb_paint_fill_glyph_func_t:+ * @funcs: paint functions object+ * @paint_data: The data accompanying the paint functions in hb_font_paint_glyph()+ * @glyph: the glyph ID+ * @font: the font+ * @is_foreground: whether the color is the foreground+ * @color: The color to use, unpremultiplied+ * @user_data: User data pointer passed to hb_paint_funcs_set_fill_glyph_func()+ *+ * A virtual method for the #hb_paint_funcs_t to fill a glyph's shape with+ * a solid color. If not implemented, a sequence of "push-clip-glyph",+ * "color", "pop-clip" paint operations, in that order, will be emitted+ * instead.+ *+ * Since: 14.3.0+ */+typedef void (*hb_paint_fill_glyph_func_t) (hb_paint_funcs_t *funcs,+ void *paint_data,+ hb_codepoint_t glyph,+ hb_font_t *font,+ hb_bool_t is_foreground,+ hb_color_t color,+ void *user_data);+/*** hb_paint_push_clip_glyph_func_t:* @funcs: paint functions object@@ -854,6 +879,23 @@ hb_paint_funcs_set_color_glyph_func (hb_paint_funcs_t *funcs,void *user_data,hb_destroy_func_t destroy);+/**+ * hb_paint_funcs_set_fill_glyph_func:+ * @funcs: A paint functions struct+ * @func: (closure user_data) (destroy destroy) (scope notified): The fill-glyph callback+ * @user_data: Data to pass to @func+ * @destroy: (nullable): Function to call when @user_data is no longer needed+ *+ * Sets the fill-glyph callback on the paint functions struct.+ *+ * Since: 14.3.0+ */+HB_EXTERN void+hb_paint_funcs_set_fill_glyph_func (hb_paint_funcs_t *funcs,+ hb_paint_fill_glyph_func_t func,+ void *user_data,+ hb_destroy_func_t destroy);+/*** hb_paint_funcs_set_push_clip_glyph_func:* @funcs: A paint functions struct@@ -1117,6 +1159,13 @@ hb_paint_color_glyph (hb_paint_funcs_t *funcs, void *paint_data,hb_codepoint_t glyph,hb_font_t *font);+HB_EXTERN void+hb_paint_fill_glyph (hb_paint_funcs_t *funcs, void *paint_data,+ hb_codepoint_t glyph,+ hb_font_t *font,+ hb_bool_t is_foreground,+ hb_color_t color);+HB_EXTERN voidhb_paint_push_clip_glyph (hb_paint_funcs_t *funcs, void *paint_data,hb_codepoint_t glyph,diff --git a/thirdparty/harfbuzz/src/hb-paint.hh b/thirdparty/harfbuzz/src/hb-paint.hhindex 148bfc974df..39135a53643 100644--- a/thirdparty/harfbuzz/src/hb-paint.hh+++ b/thirdparty/harfbuzz/src/hb-paint.hh@@ -48,6 +48,7 @@HB_PAINT_FUNC_IMPLEMENT (push_group_for) \HB_PAINT_FUNC_IMPLEMENT (pop_group) \HB_PAINT_FUNC_IMPLEMENT (custom_palette_color) \+ HB_PAINT_FUNC_IMPLEMENT (fill_glyph) \/* ^--- Add new callbacks here */struct hb_paint_funcs_t@@ -92,7 +93,7 @@ struct hb_paint_funcs_t{ return func.color_glyph (this, paint_data,glyph,font,- !user_data ? nullptr : user_data->push_clip_glyph); }+ !user_data ? nullptr : user_data->color_glyph); }void push_clip_glyph (void *paint_data,hb_codepoint_t glyph,hb_font_t *font)@@ -121,6 +122,15 @@ struct hb_paint_funcs_t{ func.color (this, paint_data,is_foreground, color,!user_data ? nullptr : user_data->color); }+ void fill_glyph (void *paint_data,+ hb_codepoint_t glyph,+ hb_font_t *font,+ hb_bool_t is_foreground,+ hb_color_t color)+ { func.fill_glyph (this, paint_data,+ glyph, font,+ is_foreground, color,+ !user_data ? nullptr : user_data->fill_glyph); }bool image (void *paint_data,hb_blob_t *image,unsigned width, unsigned height,diff --git a/thirdparty/harfbuzz/src/hb-raster-draw.cc b/thirdparty/harfbuzz/src/hb-raster-draw.ccindex ba067561a2a..b20ce0ddce7 100644--- a/thirdparty/harfbuzz/src/hb-raster-draw.cc+++ b/thirdparty/harfbuzz/src/hb-raster-draw.cc@@ -71,7 +71,26 @@ struct hb_raster_draw_thb_raster_extents_t fixed_extents = {};bool has_extents = false;+ /* Visibility clip box for curve flattening (device pixels); set+ internally by raster-paint so invisible curves collapse to their+ chord. See hb_raster_draw_set_clip_box(). */+ bool has_clip_box = false;+ float clip_x0 = 0.f, clip_y0 = 0.f, clip_x1 = 0.f, clip_y1 = 0.f;++ /* Flattening clip resolved from the above (or from fixed extents),+ expanded by one pixel; kept in sync by hb_raster_draw_update_flatten_clip(). */+ bool flatten_clip_active = false;+ float flatten_clip_x0 = 0.f, flatten_clip_y0 = 0.f;+ float flatten_clip_x1 = 0.f, flatten_clip_y1 = 0.f;++ /* Curve-flattening work, charged one unit per Bézier subdivision.+ When external_work is set (by raster-paint), that session budget+ is charged instead of the standalone per-session one. */+ int64_t flatten_work_left = HB_RASTER_MAX_DRAW_WORK;+ int64_t *external_work = nullptr;+/* Accumulated geometry */+ int64_t edges_left = HB_RASTER_MAX_DRAW_EDGES;hb_vector_t<hb_raster_edge_t> edges;/* Scratch — reused across render() calls */@@ -293,6 +312,38 @@ hb_raster_draw_get_transform (const hb_raster_draw_t *draw,if (dy) *dy = draw->transform.y0;}+/* Recompute the resolved flattening clip box: the internal clip box+ when set, otherwise the fixed output extents when known. Expanded+ by one pixel so fixed-point rounding at the boundary stays safe.+ Called whenever the clip box or extents change. A curve whose+ control-point bounding box misses the clip box entirely is replaced+ by its chord: coverage inside the box then depends only on the+ curve's endpoints (intermediate scanline crossings cancel in pairs,+ and crossings right of the box never reach visible pixels), so the+ replacement is exact for rendering. */+static void+hb_raster_draw_update_flatten_clip (hb_raster_draw_t *draw)+{+ if (draw->has_clip_box)+ {+ draw->flatten_clip_active = true;+ draw->flatten_clip_x0 = draw->clip_x0 - 1.f;+ draw->flatten_clip_y0 = draw->clip_y0 - 1.f;+ draw->flatten_clip_x1 = draw->clip_x1 + 1.f;+ draw->flatten_clip_y1 = draw->clip_y1 + 1.f;+ }+ else if (draw->has_extents)+ {+ draw->flatten_clip_active = true;+ draw->flatten_clip_x0 = (float) draw->fixed_extents.x_origin - 1.f;+ draw->flatten_clip_y0 = (float) draw->fixed_extents.y_origin - 1.f;+ draw->flatten_clip_x1 = (float) draw->fixed_extents.x_origin + (float) draw->fixed_extents.width + 1.f;+ draw->flatten_clip_y1 = (float) draw->fixed_extents.y_origin + (float) draw->fixed_extents.height + 1.f;+ }+ else+ draw->flatten_clip_active = false;+}+/*** hb_raster_draw_set_extents:* @draw: a rasterizer@@ -310,6 +361,7 @@ hb_raster_draw_set_extents (hb_raster_draw_t *draw,{draw->fixed_extents = *extents;draw->has_extents = true;+ hb_raster_draw_update_flatten_clip (draw);}/**@@ -346,6 +398,8 @@ hb_raster_draw_get_extents (const hb_raster_draw_t *draw,* This is equivalent to computing a transformed bounding box in pixel* space and calling hb_raster_draw_set_extents().*+ * The resulting dimensions are capped at 4096 pixels per side.+ ** Return value: `true` if transformed extents are non-empty and set;* `false` otherwise.*@@ -382,25 +436,27 @@ hb_raster_draw_set_glyph_extents (hb_raster_draw_t *draw,ty_max = hb_max (ty_max, ty);}- int ex0 = (int) floorf (tx_min);- int ey0 = (int) floorf (ty_min);- int ex1 = (int) ceilf (tx_max);- int ey1 = (int) ceilf (ty_max);+ int32_t ex0 = hb_clamp_to<int32_t> (floorf (tx_min));+ int32_t ey0 = hb_clamp_to<int32_t> (floorf (ty_min));+ int32_t ex1 = hb_clamp_to<int32_t> (ceilf (tx_max));+ int32_t ey1 = hb_clamp_to<int32_t> (ceilf (ty_max));if (ex1 <= ex0 || ey1 <= ey0){draw->fixed_extents = {};draw->has_extents = false;+ hb_raster_draw_update_flatten_clip (draw);return false;}draw->fixed_extents = {ex0, ey0,- (unsigned) (ex1 - ex0),- (unsigned) (ey1 - ey0),+ (unsigned) hb_min ((int64_t) ex1 - ex0, (int64_t) HB_RASTER_MAX_AUTO_DIMENSION),+ (unsigned) hb_min ((int64_t) ey1 - ey0, (int64_t) HB_RASTER_MAX_AUTO_DIMENSION),0};draw->has_extents = true;+ hb_raster_draw_update_flatten_clip (draw);return true;}@@ -420,6 +476,11 @@ hb_raster_draw_clear (hb_raster_draw_t *draw){draw->fixed_extents = {};draw->has_extents = false;+ draw->has_clip_box = false;+ draw->flatten_clip_active = false;+ draw->flatten_work_left = HB_RASTER_MAX_DRAW_WORK;+ draw->external_work = nullptr;+ draw->edges_left = HB_RASTER_MAX_DRAW_EDGES;draw->edges.clear ();draw->active_edges.clear ();}@@ -443,6 +504,36 @@ hb_raster_draw_reset (hb_raster_draw_t *draw)hb_raster_draw_clear (draw);}+void+hb_raster_draw_set_clip_box (hb_raster_draw_t *draw,+ float x0, float y0,+ float x1, float y1)+{+ draw->has_clip_box = true;+ draw->clip_x0 = x0;+ draw->clip_y0 = y0;+ draw->clip_x1 = x1;+ draw->clip_y1 = y1;+ hb_raster_draw_update_flatten_clip (draw);+}++void+hb_raster_draw_set_external_work (hb_raster_draw_t *draw,+ int64_t *work_left)+{+ draw->external_work = work_left;+}++int64_t+hb_raster_draw_get_edge_work (hb_raster_draw_t *draw, unsigned max_rows)+{+ int64_t work = 0;+ for (const auto &e : draw->edges)+ work += 1 + hb_min (((int64_t) e.yH - (int64_t) e.yL) >> HB_RASTER_PIXEL_BITS,+ (int64_t) max_rows);+ return work;+}+/*** hb_raster_draw_recycle_image:* @draw: a rasterizer@@ -483,10 +574,13 @@ emit_segment (hb_raster_draw_t *draw,float x0, float y0,float x1, float y1){- int32_t X0 = (int32_t) roundf (x0 * HB_RASTER_ONE_PIXEL);- int32_t Y0 = (int32_t) roundf (y0 * HB_RASTER_ONE_PIXEL);- int32_t X1 = (int32_t) roundf (x1 * HB_RASTER_ONE_PIXEL);- int32_t Y1 = (int32_t) roundf (y1 * HB_RASTER_ONE_PIXEL);+ if (unlikely (draw->edges_left <= 0))+ return;++ int32_t X0 = hb_clamp_to<int32_t> (roundf (x0 * HB_RASTER_ONE_PIXEL));+ int32_t Y0 = hb_clamp_to<int32_t> (roundf (y0 * HB_RASTER_ONE_PIXEL));+ int32_t X1 = hb_clamp_to<int32_t> (roundf (x1 * HB_RASTER_ONE_PIXEL));+ int32_t Y1 = hb_clamp_to<int32_t> (roundf (y1 * HB_RASTER_ONE_PIXEL));if (Y0 == Y1) return; /* horizontal — skip */@@ -499,9 +593,13 @@ emit_segment (hb_raster_draw_t *draw,e.slope = (((int64_t) e.xH - (int64_t) e.xL) * (int64_t) 65536) /((int64_t) e.yH - (int64_t) e.yL);- draw->edges.push (e);+ if (likely (draw->edges.push_or_fail (e)))+ draw->edges_left--;+ else+ draw->edges_left = 0;}+/* Quadratic Bézier flattener — iterative de Casteljau at t=0.5. */static inline voidflatten_quadratic_recursive (hb_raster_draw_t *draw,@@ -514,46 +612,90 @@ flatten_quadratic_recursive (hb_raster_draw_t *draw,{float x0, y0, x1, y1, x2, y2;int depth;+ bool check_clip;};quad_node_t stack[16];unsigned top = 0;+ bool check_clip = draw->flatten_clip_active;+ int64_t *work = draw->external_work ? draw->external_work : &draw->flatten_work_left;+ int64_t work_left = *work;+while (true){- bool is_flat;- if (false)+ bool emit_chord = depth >= 16;++ /* Entirely outside the clip box: the chord is exact for coverage.+ Subdivided control points are convex combinations of their+ parent's, so once a node is entirely inside the box no+ descendant can leave it and the test is skipped below. */+ if (!emit_chord && check_clip){- /* Old behavior: midpoint deviation from chord midpoint. */- float mx = x0 * 0.25f + x1 * 0.5f + x2 * 0.25f;- float my = y0 * 0.25f + y1 * 0.5f + y2 * 0.25f;- float chord_mx = (x0 + x2) * 0.5f;- float chord_my = (y0 + y2) * 0.5f;- float dx = mx - chord_mx;- float dy = my - chord_my;- static const float flat_thresh = HB_RASTER_FLAT_THRESH * HB_RASTER_FLAT_THRESH;- is_flat = (dx * dx + dy * dy) <= flat_thresh;+ float bx0 = hb_min (x0, hb_min (x1, x2));+ float bx1 = hb_max (x0, hb_max (x1, x2));+ float by0 = hb_min (y0, hb_min (y1, y2));+ float by1 = hb_max (y0, hb_max (y1, y2));+ if (bx1 < draw->flatten_clip_x0 || bx0 > draw->flatten_clip_x1 ||+ by1 < draw->flatten_clip_y0 || by0 > draw->flatten_clip_y1)+ emit_chord = true;+ else if (bx0 >= draw->flatten_clip_x0 && bx1 <= draw->flatten_clip_x1 &&+ by0 >= draw->flatten_clip_y0 && by1 <= draw->flatten_clip_y1)+ check_clip = false;}- else++ if (!emit_chord){- /* FreeType behavior: control-point deviation from chord center. */- const float flat_thresh = 0.25f;- float dx = x0 + x2 - 2.f * x1;- float dy = y0 + y2 - 2.f * y1;- if (dx < 0) dx = -dx;- if (dy < 0) dy = -dy;- is_flat = dx <= flat_thresh && dy <= flat_thresh;+ bool is_flat;+ if (false)+ {+ /* Old behavior: midpoint deviation from chord midpoint. */+ float mx = x0 * 0.25f + x1 * 0.5f + x2 * 0.25f;+ float my = y0 * 0.25f + y1 * 0.5f + y2 * 0.25f;+ float chord_mx = (x0 + x2) * 0.5f;+ float chord_my = (y0 + y2) * 0.5f;+ float dx = mx - chord_mx;+ float dy = my - chord_my;+ static const float flat_thresh = HB_RASTER_FLAT_THRESH * HB_RASTER_FLAT_THRESH;+ is_flat = (dx * dx + dy * dy) <= flat_thresh;+ }+ else+ {+ /* FreeType behavior: control-point deviation from chord center. */+ const float flat_thresh = 0.25f;+ float dx = x0 + x2 - 2.f * x1;+ float dy = y0 + y2 - 2.f * y1;+ if (dx < 0) dx = -dx;+ if (dy < 0) dy = -dy;+ is_flat = dx <= flat_thresh && dy <= flat_thresh;+ }+ emit_chord = is_flat;+ }++ /* Charge one unit per subdivision; degrade to the chord when the+ session work budget is spent. */+ if (!emit_chord)+ {+ if (unlikely (work_left <= 0))+ emit_chord = true;+ else+ work_left--;}- if (depth >= 16 || is_flat)+ if (emit_chord){emit_segment (draw, x0, y0, x2, y2);- if (!top) return;+ if (!top)+ {+ *work = work_left;+ return;+ }const quad_node_t &n = stack[--top];x0 = n.x0; y0 = n.y0;x1 = n.x1; y1 = n.y1;x2 = n.x2; y2 = n.y2;depth = n.depth;+ check_clip = n.check_clip;continue;}@@ -562,7 +704,7 @@ flatten_quadratic_recursive (hb_raster_draw_t *draw,float xm = (x01 + x12) * 0.5f, ym = (y01 + y12) * 0.5f;/* Depth is capped at 16, so stack capacity 16 is sufficient. */- stack[top++] = {xm, ym, x12, y12, x2, y2, depth + 1};+ stack[top++] = {xm, ym, x12, y12, x2, y2, depth + 1, check_clip};x2 = xm; y2 = ym;x1 = x01; y1 = y01;depth++;@@ -680,52 +822,96 @@ flatten_cubic_recursive (hb_raster_draw_t *draw,{float x0, y0, x1, y1, x2, y2, x3, y3;int depth;+ bool check_clip;};cubic_node_t stack[16];unsigned top = 0;+ bool check_clip = draw->flatten_clip_active;+ int64_t *work = draw->external_work ? draw->external_work : &draw->flatten_work_left;+ int64_t work_left = *work;+while (true){- bool is_flat;- if (false)+ bool emit_chord = depth >= 16;++ /* Entirely outside the clip box: the chord is exact for coverage.+ Subdivided control points are convex combinations of their+ parent's, so once a node is entirely inside the box no+ descendant can leave it and the test is skipped below. */+ if (!emit_chord && check_clip){- /* Old behavior: curvature/chord-error bound. */- float err2 = cubic_chord_error_bound2 (x0, y0, x1, y1, x2, y2, x3, y3);- static const float flat_thresh = HB_RASTER_FLAT_THRESH * HB_RASTER_FLAT_THRESH;- is_flat = err2 <= flat_thresh;+ float bx0 = hb_min (hb_min (x0, x1), hb_min (x2, x3));+ float bx1 = hb_max (hb_max (x0, x1), hb_max (x2, x3));+ float by0 = hb_min (hb_min (y0, y1), hb_min (y2, y3));+ float by1 = hb_max (hb_max (y0, y1), hb_max (y2, y3));+ if (bx1 < draw->flatten_clip_x0 || bx0 > draw->flatten_clip_x1 ||+ by1 < draw->flatten_clip_y0 || by0 > draw->flatten_clip_y1)+ emit_chord = true;+ else if (bx0 >= draw->flatten_clip_x0 && bx1 <= draw->flatten_clip_x1 &&+ by0 >= draw->flatten_clip_y0 && by1 <= draw->flatten_clip_y1)+ check_clip = false;}- else++ if (!emit_chord){- /* FreeType behavior: chord-trisection distance test. */- const float flat_thresh = 0.5f;-- float d10x = 2.f * x0 - 3.f * x1 + x3;- float d10y = 2.f * y0 - 3.f * y1 + y3;- float d20x = x0 - 3.f * x2 + 2.f * x3;- float d20y = y0 - 3.f * y2 + 2.f * y3;-- if (d10x < 0) d10x = -d10x;- if (d10y < 0) d10y = -d10y;- if (d20x < 0) d20x = -d20x;- if (d20y < 0) d20y = -d20y;-- is_flat = d10x <= flat_thresh &&- d10y <= flat_thresh &&- d20x <= flat_thresh &&- d20y <= flat_thresh;+ bool is_flat;+ if (false)+ {+ /* Old behavior: curvature/chord-error bound. */+ float err2 = cubic_chord_error_bound2 (x0, y0, x1, y1, x2, y2, x3, y3);+ static const float flat_thresh = HB_RASTER_FLAT_THRESH * HB_RASTER_FLAT_THRESH;+ is_flat = err2 <= flat_thresh;+ }+ else+ {+ /* FreeType behavior: chord-trisection distance test. */+ const float flat_thresh = 0.5f;++ float d10x = 2.f * x0 - 3.f * x1 + x3;+ float d10y = 2.f * y0 - 3.f * y1 + y3;+ float d20x = x0 - 3.f * x2 + 2.f * x3;+ float d20y = y0 - 3.f * y2 + 2.f * y3;++ if (d10x < 0) d10x = -d10x;+ if (d10y < 0) d10y = -d10y;+ if (d20x < 0) d20x = -d20x;+ if (d20y < 0) d20y = -d20y;++ is_flat = d10x <= flat_thresh &&+ d10y <= flat_thresh &&+ d20x <= flat_thresh &&+ d20y <= flat_thresh;+ }+ emit_chord = is_flat;+ }++ /* Charge one unit per subdivision; degrade to the chord when the+ session work budget is spent. */+ if (!emit_chord)+ {+ if (unlikely (work_left <= 0))+ emit_chord = true;+ else+ work_left--;}- if (depth >= 16 || is_flat)+ if (emit_chord){emit_segment (draw, x0, y0, x3, y3);- if (!top) return;+ if (!top)+ {+ *work = work_left;+ return;+ }const cubic_node_t &n = stack[--top];x0 = n.x0; y0 = n.y0;x1 = n.x1; y1 = n.y1;x2 = n.x2; y2 = n.y2;x3 = n.x3; y3 = n.y3;depth = n.depth;+ check_clip = n.check_clip;continue;}@@ -737,7 +923,7 @@ flatten_cubic_recursive (hb_raster_draw_t *draw,float xm = (x012 + x123) * 0.5f, ym = (y012 + y123) * 0.5f;/* Depth is capped at 16, so stack capacity 16 is sufficient. */- stack[top++] = {xm, ym, x123, y123, x23, y23, x3, y3, depth + 1};+ stack[top++] = {xm, ym, x123, y123, x23, y23, x3, y3, depth + 1, check_clip};x3 = xm; y3 = ym;x2 = x012; y2 = y012;x1 = x01; y1 = y01;@@ -850,6 +1036,7 @@ hb_raster_line_to (hb_draw_funcs_t *dfuncs HB_UNUSED,void *user_data HB_UNUSED){hb_raster_draw_t *draw = (hb_raster_draw_t *) draw_data;+ if (unlikely (draw->edges_left <= 0)) return;float tx0, ty0, tx1, ty1;transform_point (draw, st->current_x, st->current_y, tx0, ty0);@@ -866,6 +1053,7 @@ hb_raster_quadratic_to (hb_draw_funcs_t *dfuncs HB_UNUSED,void *user_data HB_UNUSED){hb_raster_draw_t *draw = (hb_raster_draw_t *) draw_data;+ if (unlikely (draw->edges_left <= 0)) return;float tx0, ty0, tx1, ty1, tx2, ty2;transform_point (draw, st->current_x, st->current_y, tx0, ty0);@@ -884,6 +1072,7 @@ hb_raster_cubic_to (hb_draw_funcs_t *dfuncs HB_UNUSED,void *user_data HB_UNUSED){hb_raster_draw_t *draw = (hb_raster_draw_t *) draw_data;+ if (unlikely (draw->edges_left <= 0)) return;float tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3;transform_point (draw, st->current_x, st->current_y, tx0, ty0);@@ -1057,7 +1246,10 @@ edge_sweep_row (int32_t *area,unsigned &x_min,unsigned &x_max){- int32_t y_bot = y_top + HB_RASTER_ONE_PIXEL;+ /* Saturate: y_top can be within ONE_PIXEL of INT32_MAX when the surface+ * sits at the extreme of the fixed-point coordinate space. Edges are+ * int32-clamped too, so no coverage exists beyond INT32_MAX anyway. */+ int32_t y_bot = (int32_t) hb_min ((int64_t) y_top + HB_RASTER_ONE_PIXEL, (int64_t) INT32_MAX);int32_t ey0 = hb_max (edge.yL, y_top);int32_t ey1 = hb_min (edge.yH, y_bot);@@ -1289,16 +1481,18 @@ hb_raster_draw_render (hb_raster_draw_t *draw)ymax = hb_max (ymax, e.yH);}- /* Convert fixed-point → pixels (floor for min, ceil for max) */+ /* Convert fixed-point → pixels (floor for min, ceil for max). Edge+ coordinates are saturated to int32 range in emit_segment, so the+ +MASK ceil step must be widened to avoid signed overflow. */int x0 = xmin >> HB_RASTER_PIXEL_BITS;int y0 = ymin >> HB_RASTER_PIXEL_BITS;- int x1 = (xmax + HB_RASTER_PIXEL_MASK) >> HB_RASTER_PIXEL_BITS;- int y1 = (ymax + HB_RASTER_PIXEL_MASK) >> HB_RASTER_PIXEL_BITS;+ int x1 = (int) (((int64_t) xmax + HB_RASTER_PIXEL_MASK) >> HB_RASTER_PIXEL_BITS);+ int y1 = (int) (((int64_t) ymax + HB_RASTER_PIXEL_MASK) >> HB_RASTER_PIXEL_BITS);ext.x_origin = x0;ext.y_origin = y0;- ext.width = (unsigned) hb_max (0, x1 - x0);- ext.height = (unsigned) hb_max (0, y1 - y0);+ ext.width = (unsigned) hb_min (hb_max (0, x1 - x0), HB_RASTER_MAX_AUTO_DIMENSION);+ ext.height = (unsigned) hb_min (hb_max (0, y1 - y0), HB_RASTER_MAX_AUTO_DIMENSION);ext.stride = 0; /* filled below */}}diff --git a/thirdparty/harfbuzz/src/hb-raster-image.cc b/thirdparty/harfbuzz/src/hb-raster-image.ccindex baf825279cb..14b7089eb02 100644--- a/thirdparty/harfbuzz/src/hb-raster-image.cc+++ b/thirdparty/harfbuzz/src/hb-raster-image.cc@@ -30,6 +30,56 @@#include <math.h>+/**+ * SECTION:hb-raster+ * @title: hb-raster+ * @short_description: Glyph rasterization+ * @include: hb-raster.h+ *+ * Functions for rasterizing glyph outlines into pixel buffers.+ *+ * #hb_raster_draw_t rasterizes outline geometry and always outputs+ * @HB_RASTER_FORMAT_A8. Typical flow:+ *+ * |[<!-- language="plain" -->+ * hb_raster_draw_t *draw = hb_raster_draw_create_or_fail ();+ * hb_raster_draw_set_scale_factor (draw, 64.f, 64.f);+ * hb_raster_draw_set_transform (draw, 1.f, 0.f, 0.f, 1.f, 0.f, 0.f);+ * hb_glyph_extents_t glyph_extents;+ * hb_font_get_glyph_extents (font, gid, &glyph_extents);+ * hb_raster_draw_set_glyph_extents (draw, &glyph_extents);+ * hb_raster_draw_glyph (draw, font, gid);+ * hb_raster_image_t *mask = hb_raster_draw_render (draw);+ * hb_raster_extents_t image_extents;+ * hb_raster_image_get_extents (mask, &image_extents);+ * ]|+ *+ * #hb_raster_paint_t renders color paint graphs and always outputs+ * @HB_RASTER_FORMAT_BGRA32. Typical flow:+ *+ * |[<!-- language="plain" -->+ * hb_raster_paint_t *paint = hb_raster_paint_create_or_fail ();+ * hb_raster_paint_set_scale_factor (paint, 64.f, 64.f);+ * hb_raster_paint_set_transform (paint, 1.f, 0.f, 0.f, 1.f, 0.f, 0.f);+ * hb_raster_paint_set_foreground (paint, foreground);+ * hb_glyph_extents_t glyph_extents;+ * hb_font_get_glyph_extents (font, gid, &glyph_extents);+ * hb_raster_paint_set_glyph_extents (paint, &glyph_extents);+ * hb_raster_paint_glyph (paint, font, gid);+ * hb_raster_image_t *img = hb_raster_paint_render (paint);+ * hb_raster_extents_t image_extents;+ * hb_raster_image_get_extents (img, &image_extents);+ * ]|+ *+ * In both modes, set extents explicitly (or via glyph extents) before+ * rendering to avoid implicit allocations and to get deterministic bounds.+ * When caching individual glyph images for later composition, position each+ * image using the `x_origin` and `y_origin` members returned by+ * hb_raster_image_get_extents(). These are the pixel-space left and bottom+ * edges after raster-bound rounding; do not reconstruct them from glyph+ * bearings and image dimensions.+ **/+#ifdef HAVE_PNG#include <png.h>#endif@@ -579,7 +629,8 @@ hb_raster_image_t::deserialize_from_png (hb_blob_t *blob)}size_t rgba_size = (size_t) rowbytes * (size_t) h;- if (h && rgba_size / (size_t) h != (size_t) rowbytes)+ if ((h && rgba_size / (size_t) h != (size_t) rowbytes) ||+ rgba_size > HB_RASTER_MAX_BUFFER_SIZE){png_destroy_read_struct (&png, &info, nullptr);hb_raster_png_read_blob_fini (reader);diff --git a/thirdparty/harfbuzz/src/hb-raster-paint.cc b/thirdparty/harfbuzz/src/hb-raster-paint.ccindex d5bcdd8b343..1cb710d4637 100644--- a/thirdparty/harfbuzz/src/hb-raster-paint.cc+++ b/thirdparty/harfbuzz/src/hb-raster-paint.cc@@ -107,6 +107,21 @@ ensure_initialized (hb_raster_paint_t *c){if (c->surface_stack.length) return;+ /* A failed stack push (OOM) leaves the vector in a sticky error+ * state, so initialization can never succeed; bail out cheaply+ * instead of re-paying the surface acquire-and-clear below on+ * every subsequent paint callback. */+ if (unlikely (c->surface_stack.in_error () || c->clip_stack.in_error ()))+ return;++ /* acquire_surface() clears a full surface; charge its area, so+ * repeated failed initialization attempts cannot re-pay it+ * indefinitely. Successful initialization re-arms the session+ * budget below, making the charge a no-op for normal sessions. */+ if (unlikely (!c->charge_work ((int64_t) c->fixed_extents.width *+ c->fixed_extents.height)))+ return;+/* Root surface */hb_raster_image_t *root = c->acquire_surface ();if (unlikely (!root)) return;@@ -134,12 +149,17 @@ ensure_initialized (hb_raster_paint_t *c)return;}+ /* Session work budget: flat floor, or a few passes over the (possibly+ * client-sized) surface, whichever is larger. */+ c->work_left = hb_max ((int64_t) HB_RASTER_MAX_PAINT_WORK,+ (int64_t) HB_RASTER_MAX_PAINT_WORK_PASSES *+ c->fixed_extents.width * c->fixed_extents.height);+/* Initial clip: full coverage rectangle */hb_raster_clip_t clip;clip.init_full (c->fixed_extents.width, c->fixed_extents.height);if (unlikely (!c->clip_stack.push_or_fail (std::move (clip)))){- c->transform_stack.pop ();c->release_surface (c->surface_stack.pop ());return;}@@ -184,6 +204,23 @@ hb_raster_paint_color_glyph (hb_paint_funcs_t *pfuncs HB_UNUSED,typedef void (*hb_raster_paint_clip_mask_emit_t) (hb_raster_draw_t *rdr, void *user_data);+/* Attach the surface box and the session work budget to @rdr before+ * outlines are drawn into it: curves outside the surface collapse to+ * their chord, and flattening work is charged as it happens instead+ * of only after the whole outline has been emitted. */+static void+hb_raster_paint_attach_clip_rdr (hb_raster_paint_t *c,+ hb_raster_draw_t *rdr,+ const hb_raster_image_t *surf)+{+ hb_raster_draw_set_clip_box (rdr,+ (float) surf->extents.x_origin,+ (float) surf->extents.y_origin,+ (float) surf->extents.x_origin + (float) surf->extents.width,+ (float) surf->extents.y_origin + (float) surf->extents.height);+ hb_raster_draw_set_external_work (rdr, &c->work_left);+}+static voidhb_raster_paint_push_empty_clip (hb_raster_paint_t *c, unsigned w, unsigned h){@@ -196,6 +233,35 @@ hb_raster_paint_push_empty_clip (hb_raster_paint_t *c, unsigned w, unsigned h)(void) c->clip_stack.push (std::move (new_clip));}+static bool+hb_raster_paint_intersect_mask (const hb_raster_image_t *surf,+ const hb_raster_extents_t &mask_ext,+ const hb_raster_clip_t &clip,+ unsigned w, unsigned h,+ int64_t *mask_x0, int64_t *mask_y0,+ unsigned *ix0, unsigned *iy0,+ unsigned *ix1, unsigned *iy1)+{+ /* Convert mask extents from surface coordinates to clip-buffer coordinates. */+ int64_t mx0 = (int64_t) mask_ext.x_origin - (int64_t) surf->extents.x_origin;+ int64_t my0 = (int64_t) mask_ext.y_origin - (int64_t) surf->extents.y_origin;++ int64_t x0 = hb_max ((int64_t) clip.min_x, hb_max (mx0, (int64_t) 0));+ int64_t y0 = hb_max ((int64_t) clip.min_y, hb_max (my0, (int64_t) 0));+ int64_t x1 = hb_min ((int64_t) clip.max_x, hb_min (mx0 + mask_ext.width, (int64_t) w));+ int64_t y1 = hb_min ((int64_t) clip.max_y, hb_min (my0 + mask_ext.height, (int64_t) h));++ if (x0 >= x1 || y0 >= y1) return false;++ *mask_x0 = mx0;+ *mask_y0 = my0;+ *ix0 = (unsigned) x0;+ *iy0 = (unsigned) y0;+ *ix1 = (unsigned) x1;+ *iy1 = (unsigned) y1;+ return true;+}+/* Render whatever edges have been accumulated into @rdr and* push the result as a new clip on the stack, intersecting* with the existing clip. Used by the emitter-based clip@@ -207,6 +273,10 @@ hb_raster_paint_finalize_path_clip (hb_raster_paint_t *c,hb_raster_image_t *surf,unsigned w, unsigned h){+ /* Charge the scanline work of the accumulated outline before+ * rendering it. */+ c->work_left -= hb_raster_draw_get_edge_work (rdr, h);+hb_raster_image_t *mask_img = hb_raster_draw_render (rdr);if (unlikely (!mask_img))@@ -215,6 +285,18 @@ hb_raster_paint_finalize_path_clip (hb_raster_paint_t *c,return;}+ /* Charge the mask render (its own area; may exceed the surface) plus+ * the clip-buffer pass below. */+ hb_raster_extents_t mask_render_ext;+ hb_raster_image_get_extents (mask_img, &mask_render_ext);+ if (unlikely (!c->charge_work ((int64_t) mask_render_ext.width * mask_render_ext.height ++ (int64_t) w * h)))+ {+ hb_raster_draw_recycle_image (rdr, mask_img);+ hb_raster_paint_push_empty_clip (c, w, h);+ return;+ }+hb_raster_clip_t new_clip = c->acquire_clip (w, h);/* Allocate alpha buffer and intersect with previous clip */@@ -239,29 +321,17 @@ hb_raster_paint_finalize_path_clip (hb_raster_paint_t *c,return;}- /* Convert mask extents from surface coordinates to clip-buffer coordinates. */- int mask_x0 = mask_ext.x_origin - surf->extents.x_origin;- int mask_y0 = mask_ext.y_origin - surf->extents.y_origin;- int mask_x1 = mask_x0 + (int) mask_ext.width;- int mask_y1 = mask_y0 + (int) mask_ext.height;-- int ix0_i = hb_max ((int) old_clip.min_x, hb_max (mask_x0, 0));- int iy0_i = hb_max ((int) old_clip.min_y, hb_max (mask_y0, 0));- int ix1_i = hb_min ((int) old_clip.max_x, hb_min (mask_x1, (int) w));- int iy1_i = hb_min ((int) old_clip.max_y, hb_min (mask_y1, (int) h));-- if (ix0_i >= ix1_i || iy0_i >= iy1_i)+ int64_t mask_x0, mask_y0;+ unsigned ix0, iy0, ix1, iy1;+ if (!hb_raster_paint_intersect_mask (surf, mask_ext, old_clip, w, h,+ &mask_x0, &mask_y0,+ &ix0, &iy0, &ix1, &iy1)){hb_raster_draw_recycle_image (rdr, mask_img);hb_raster_paint_push_empty_clip (c, w, h);return;}- unsigned ix0 = (unsigned) ix0_i;- unsigned iy0 = (unsigned) iy0_i;- unsigned ix1 = (unsigned) ix1_i;- unsigned iy1 = (unsigned) iy1_i;-new_clip.min_x = w; new_clip.min_y = h;new_clip.max_x = 0; new_clip.max_y = 0;@@ -269,11 +339,11 @@ hb_raster_paint_finalize_path_clip (hb_raster_paint_t *c,{for (unsigned y = iy0; y < iy1; y++){- const uint8_t *mask_row = mask_buf + (unsigned) ((int) y - mask_y0) * mask_ext.stride;+ const uint8_t *mask_row = mask_buf + (unsigned) ((int64_t) y - mask_y0) * mask_ext.stride;uint8_t *out_row = new_clip.alpha.arrayZ + y * new_clip.stride;unsigned row_min = ix1;unsigned row_max = ix0;- unsigned mx = (unsigned) ((int) ix0 - mask_x0);+ unsigned mx = (unsigned) ((int64_t) ix0 - mask_x0);for (unsigned x = ix0; x < ix1; x++){uint8_t a = mask_row[mx++];@@ -300,13 +370,13 @@ hb_raster_paint_finalize_path_clip (hb_raster_paint_t *c,for (unsigned y = iy0; y < iy1; y++){const uint8_t *old_row = old_clip.alpha.arrayZ + y * old_clip.stride;- const uint8_t *mask_row = mask_buf + (unsigned) ((int) y - mask_y0) * mask_ext.stride;+ const uint8_t *mask_row = mask_buf + (unsigned) ((int64_t) y - mask_y0) * mask_ext.stride;uint8_t *out_row = new_clip.alpha.arrayZ + y * new_clip.stride;unsigned row_min = ix1;unsigned row_max = ix0;for (unsigned x = ix0; x < ix1; x++){- unsigned mx = (unsigned) ((int) x - mask_x0);+ unsigned mx = (unsigned) ((int64_t) x - mask_x0);uint8_t a = hb_raster_div255 (mask_row[mx] * old_row[x]);out_row[x] = a;if (a)@@ -343,9 +413,19 @@ hb_raster_paint_push_clip_from_emitter (hb_raster_paint_t *c,unsigned w = surf->extents.width;unsigned h = surf->extents.height;+ /* Out of budget: skip the glyph-outline extraction entirely, so+ * per-glyph outline limits cannot multiply with the caller's+ * paint-graph traversal limits. */+ if (unlikely (c->work_left <= 0))+ {+ hb_raster_paint_push_empty_clip (c, w, h);+ return;+ }+hb_raster_draw_t *rdr = c->clip_rdr;hb_transform_t<> t = c->current_effective_transform ();hb_raster_draw_set_transform (rdr, t.xx, t.yx, t.xy, t.yy, t.x0, t.y0);+ hb_raster_paint_attach_clip_rdr (c, rdr, surf);emit (rdr, emit_data);hb_raster_paint_finalize_path_clip (c, rdr, surf, w, h);@@ -416,10 +496,14 @@ hb_raster_paint_push_clip_rectangle (hb_paint_funcs_t *pfuncs HB_UNUSED,fmax_x = hb_max (fmax_x, cx[i]); fmax_y = hb_max (fmax_y, cy[i]);}- int px0 = (int) floorf (fmin_x) - surf->extents.x_origin;- int py0 = (int) floorf (fmin_y) - surf->extents.y_origin;- int px1 = (int) ceilf (fmax_x) - surf->extents.x_origin;- int py1 = (int) ceilf (fmax_y) - surf->extents.y_origin;+ /* A spec-legal but very large transform can push these bounds past the int+ range or to non-finite values; a bare float->int conversion would then be+ undefined. Saturate through hb_clamp_to<> (which also maps NaN to+ INT32_MIN); the subtraction is done in double to avoid overflow. */+ int px0 = hb_clamp_to<int32_t> ((double) floorf (fmin_x) - surf->extents.x_origin);+ int py0 = hb_clamp_to<int32_t> ((double) floorf (fmin_y) - surf->extents.y_origin);+ int px1 = hb_clamp_to<int32_t> ((double) ceilf (fmax_x) - surf->extents.x_origin);+ int py1 = hb_clamp_to<int32_t> ((double) ceilf (fmax_y) - surf->extents.y_origin);/* Clamp to surface bounds */px0 = hb_max (px0, 0);@@ -434,6 +518,14 @@ hb_raster_paint_push_clip_rectangle (hb_paint_funcs_t *pfuncs HB_UNUSED,return;}+ /* All paths below except rect-on-rect run a full clip-buffer pass. */+ if (!(is_axis_aligned && old_clip.is_rect) &&+ unlikely (!c->charge_work ((int64_t) w * h)))+ {+ hb_raster_paint_push_empty_clip (c, w, h);+ return;+ }+hb_raster_clip_t new_clip = c->acquire_clip (w, h);if (is_axis_aligned && old_clip.is_rect)@@ -631,6 +723,9 @@ hb_raster_paint_push_clip_path_start (hb_paint_funcs_t *pfuncs HB_UNUSED,hb_raster_draw_t *rdr = c->clip_rdr;hb_transform_t<> t = c->current_effective_transform ();hb_raster_draw_set_transform (rdr, t.xx, t.yx, t.xy, t.yy, t.x0, t.y0);+ hb_raster_image_t *surf = c->current_surface ();+ if (likely (surf))+ hb_raster_paint_attach_clip_rdr (c, rdr, surf);*draw_data = rdr;return hb_raster_draw_get_funcs (rdr);@@ -649,6 +744,13 @@ hb_raster_paint_push_clip_path_end (hb_paint_funcs_t *pfuncs HB_UNUSED,unsigned w = surf->extents.width;unsigned h = surf->extents.height;+ if (unlikely (c->work_left <= 0))+ {+ hb_raster_draw_clear (c->clip_rdr);+ hb_raster_paint_push_empty_clip (c, w, h);+ return;+ }+hb_raster_paint_finalize_path_clip (c, c->clip_rdr, surf, w, h);}@@ -671,6 +773,10 @@ hb_raster_paint_push_group (hb_paint_funcs_t *pfuncs HB_UNUSED,ensure_initialized (c);+ /* acquire_surface() clears a full surface; charge its area. */+ if (unlikely (!c->charge_work ((int64_t) c->fixed_extents.width * c->fixed_extents.height)))+ return;+hb_raster_image_t *new_surf = c->acquire_surface ();if (unlikely (!new_surf)) return;if (unlikely (!c->surface_stack.push_or_fail (new_surf)))@@ -690,26 +796,19 @@ hb_raster_paint_pop_group (hb_paint_funcs_t *pfuncs HB_UNUSED,hb_raster_image_t *src = c->surface_stack.pop ();hb_raster_image_t *dst = c->current_surface ();- if (dst && src)+ if (dst && src &&+ likely (c->charge_work ((int64_t) dst->extents.width * dst->extents.height)))hb_raster_image_composite (dst, src, mode);c->release_surface (src);}static void-hb_raster_paint_color (hb_paint_funcs_t *pfuncs HB_UNUSED,- void *paint_data,- hb_bool_t is_foreground HB_UNUSED,+hb_raster_paint_solid (hb_raster_paint_t *c,+ hb_raster_image_t *surf,hb_color_t color,- void *user_data HB_UNUSED)+ hb_raster_image_t *mask_img){- hb_raster_paint_t *c = (hb_raster_paint_t *) paint_data;-- ensure_initialized (c);-- hb_raster_image_t *surf = c->current_surface ();- if (unlikely (!surf)) return;-uint32_t premul = color_to_premul_pixel (color);uint8_t premul_a = (uint8_t) (premul >> 24);const hb_raster_clip_t &clip = c->current_clip ();@@ -718,15 +817,39 @@ hb_raster_paint_color (hb_paint_funcs_t *pfuncs HB_UNUSED,if (clip.min_x >= clip.max_x || clip.min_y >= clip.max_y) return;if (premul_a == 0) return;+ unsigned ix0 = clip.min_x, iy0 = clip.min_y;+ unsigned ix1 = clip.max_x, iy1 = clip.max_y;+ const uint8_t *mask_buf = nullptr;+ hb_raster_extents_t mask_ext;+ int64_t mask_x0 = 0, mask_y0 = 0;+ if (mask_img)+ {+ mask_buf = hb_raster_image_get_buffer (mask_img);+ hb_raster_image_get_extents (mask_img, &mask_ext);+ if (!hb_raster_paint_intersect_mask (surf, mask_ext, clip,+ surf->extents.width, surf->extents.height,+ &mask_x0, &mask_y0,+ &ix0, &iy0, &ix1, &iy1))+ return;+ }++ if (unlikely (!c->charge_work ((int64_t) (ix1 - ix0) * (iy1 - iy0))))+ return;+if (likely (!clip.is_rect)){- for (unsigned y = clip.min_y; y < clip.max_y; y++)+ for (unsigned y = iy0; y < iy1; y++){hb_packed_t<uint32_t> *__restrict row = (hb_packed_t<uint32_t> *) (surf->buffer.arrayZ + y * stride);const uint8_t *__restrict clip_row = clip.alpha.arrayZ + y * clip.stride;- for (unsigned x = clip.min_x; x < clip.max_x; x++)+ const uint8_t *__restrict mask_row = mask_buf ? mask_buf + (unsigned) ((int64_t) y - mask_y0) * mask_ext.stride+ : nullptr;+ unsigned mx = (unsigned) ((int64_t) ix0 - mask_x0);+ for (unsigned x = ix0; x < ix1; x++){uint8_t clip_alpha = clip_row[x];+ if (mask_row)+ clip_alpha = hb_raster_div255 (mask_row[mx++] * clip_alpha);if (clip_alpha == 0) continue;if (clip_alpha == 255){@@ -743,6 +866,22 @@ hb_raster_paint_color (hb_paint_funcs_t *pfuncs HB_UNUSED,}}}+ else if (mask_buf)+ {+ for (unsigned y = iy0; y < iy1; y++)+ {+ hb_packed_t<uint32_t> *__restrict row = (hb_packed_t<uint32_t> *) (surf->buffer.arrayZ + y * stride);+ const uint8_t *__restrict mask_row = mask_buf + (unsigned) ((int64_t) y - mask_y0) * mask_ext.stride;+ unsigned mx = (unsigned) ((int64_t) ix0 - mask_x0);+ for (unsigned x = ix0; x < ix1; x++)+ {+ uint8_t mask_alpha = mask_row[mx++];+ if (mask_alpha == 0) continue;+ uint32_t src = hb_raster_alpha_mul (premul, mask_alpha);+ row[x] = hb_packed_t<uint32_t> (hb_raster_src_over (src, (uint32_t) row[x]));+ }+ }+ }else{for (unsigned y = clip.min_y; y < clip.max_y; y++)@@ -754,6 +893,65 @@ hb_raster_paint_color (hb_paint_funcs_t *pfuncs HB_UNUSED,}}+static void+hb_raster_paint_color (hb_paint_funcs_t *pfuncs HB_UNUSED,+ void *paint_data,+ hb_bool_t is_foreground HB_UNUSED,+ hb_color_t color,+ void *user_data HB_UNUSED)+{+ hb_raster_paint_t *c = (hb_raster_paint_t *) paint_data;++ ensure_initialized (c);++ hb_raster_image_t *surf = c->current_surface ();+ if (unlikely (!surf)) return;++ hb_raster_paint_solid (c, surf, color, nullptr);+}++static void+hb_raster_paint_fill_glyph (hb_paint_funcs_t *pfuncs HB_UNUSED,+ void *paint_data,+ hb_codepoint_t glyph,+ hb_font_t *font,+ hb_bool_t is_foreground HB_UNUSED,+ hb_color_t color,+ void *user_data HB_UNUSED)+{+ hb_raster_paint_t *c = (hb_raster_paint_t *) paint_data;++ ensure_initialized (c);++ hb_raster_image_t *surf = c->current_surface ();+ if (unlikely (!surf)) return;++ /* Out of budget: skip the glyph-outline extraction entirely. */+ if (unlikely (c->work_left <= 0)) return;++ hb_raster_draw_t *rdr = c->clip_rdr;+ hb_transform_t<> t = c->current_effective_transform ();+ hb_raster_draw_set_transform (rdr, t.xx, t.yx, t.xy, t.yy, t.x0, t.y0);+ hb_raster_paint_attach_clip_rdr (c, rdr, surf);++ hb_raster_paint_glyph_clip_data_t data = {glyph, font};+ hb_raster_paint_emit_clip_glyph_mask (rdr, &data);++ /* Charge the scanline work of the accumulated outline before+ * rendering it. */+ c->work_left -= hb_raster_draw_get_edge_work (rdr, surf->extents.height);++ hb_raster_image_t *mask_img = hb_raster_draw_render (rdr);+ if (unlikely (!mask_img)) return;++ hb_raster_extents_t mask_ext;+ hb_raster_image_get_extents (mask_img, &mask_ext);+ if (likely (c->charge_work ((int64_t) mask_ext.width * mask_ext.height)))+ hb_raster_paint_solid (c, surf, color, mask_img);++ hb_raster_draw_recycle_image (rdr, mask_img);+}+static hb_bool_thb_raster_paint_image (hb_paint_funcs_t *pfuncs HB_UNUSED,void *paint_data,@@ -769,6 +967,9 @@ hb_raster_paint_image (hb_paint_funcs_t *pfuncs HB_UNUSED,ensure_initialized (c);+ /* Out of budget: skip, including the image decode below. */+ if (unlikely (c->work_left <= 0)) return false;+unsigned src_width = width;unsigned src_height = height;const hb_packed_t<uint32_t> *src_data = nullptr;@@ -839,6 +1040,14 @@ hb_raster_paint_image (hb_paint_funcs_t *pfuncs HB_UNUSED,if (fabsf (img_sx) < 1e-10f || fabsf (img_sy) < 1e-10f)return false;+ {+ unsigned clip_w = clip.max_x > clip.min_x ? clip.max_x - clip.min_x : 0;+ unsigned clip_h = clip.max_y > clip.min_y ? clip.max_y - clip.min_y : 0;+ if (unlikely (!c->charge_work ((int64_t) clip_w * clip_h ++ (int64_t) src_width * src_height)))+ return false;+ }+if (clip.is_rect){for (unsigned py = clip.min_y; py < clip.max_y; py++)@@ -852,7 +1061,8 @@ hb_raster_paint_image (hb_paint_funcs_t *pfuncs HB_UNUSED,float ix = (gx - img_x) / img_sx;float iy = (float) (src_height - 1) - (gy - img_y) / img_sy;- if (ix < 0.f || iy < 0.f ||+ if (unlikely (!std::isfinite (ix) || !std::isfinite (iy)) ||+ ix < 0.f || iy < 0.f ||ix > (float) (src_width - 1) || iy > (float) (src_height - 1)){gx += inv_xx;@@ -890,7 +1100,8 @@ hb_raster_paint_image (hb_paint_funcs_t *pfuncs HB_UNUSED,float ix = (gx - img_x) / img_sx;float iy = (float) (src_height - 1) - (gy - img_y) / img_sy;- if (ix < 0.f || iy < 0.f ||+ if (unlikely (!std::isfinite (ix) || !std::isfinite (iy)) ||+ ix < 0.f || iy < 0.f ||ix > (float) (src_width - 1) || iy > (float) (src_height - 1)){gx += inv_xx;@@ -1068,6 +1279,8 @@ hb_raster_paint_linear_gradient (hb_paint_funcs_t *pfuncs HB_UNUSED,const hb_raster_clip_t &clip = c->current_clip ();unsigned clip_w = clip.max_x > clip.min_x ? clip.max_x - clip.min_x : 0;unsigned clip_h = clip.max_y > clip.min_y ? clip.max_y - clip.min_y : 0;+ if (unlikely (!c->charge_work ((int64_t) clip_w * clip_h)))+ return;bool use_lut = (uint64_t) clip_w * clip_h >= GRADIENT_LUT_MIN_PIXELS;uint32_t lut[GRADIENT_LUT_SIZE];if (use_lut)@@ -1217,6 +1430,8 @@ hb_raster_paint_radial_gradient (hb_paint_funcs_t *pfuncs HB_UNUSED,const hb_raster_clip_t &clip = c->current_clip ();unsigned clip_w = clip.max_x > clip.min_x ? clip.max_x - clip.min_x : 0;unsigned clip_h = clip.max_y > clip.min_y ? clip.max_y - clip.min_y : 0;+ if (unlikely (!c->charge_work ((int64_t) clip_w * clip_h)))+ return;bool use_lut = (uint64_t) clip_w * clip_h >= GRADIENT_LUT_MIN_PIXELS;uint32_t lut[GRADIENT_LUT_SIZE];if (use_lut)@@ -1493,6 +1708,8 @@ hb_raster_paint_sweep_gradient (hb_paint_funcs_t *pfuncs HB_UNUSED,const hb_raster_clip_t &clip = c->current_clip ();unsigned clip_w = clip.max_x > clip.min_x ? clip.max_x - clip.min_x : 0;unsigned clip_h = clip.max_y > clip.min_y ? clip.max_y - clip.min_y : 0;+ if (unlikely (!c->charge_work ((int64_t) clip_w * clip_h)))+ return;bool use_lut = (uint64_t) clip_w * clip_h >= GRADIENT_LUT_MIN_PIXELS;uint32_t lut[GRADIENT_LUT_SIZE];if (use_lut)@@ -1645,6 +1862,7 @@ static struct hb_raster_paint_funcs_lazy_loader_t : hb_paint_funcs_lazy_loader_thb_paint_funcs_set_push_transform_func (funcs, hb_raster_paint_push_transform, nullptr, nullptr);hb_paint_funcs_set_pop_transform_func (funcs, hb_raster_paint_pop_transform, nullptr, nullptr);+ hb_paint_funcs_set_fill_glyph_func (funcs, hb_raster_paint_fill_glyph, nullptr, nullptr);hb_paint_funcs_set_color_glyph_func (funcs, hb_raster_paint_color_glyph, nullptr, nullptr);hb_paint_funcs_set_push_clip_glyph_func (funcs, hb_raster_paint_push_clip_glyph, nullptr, nullptr);hb_paint_funcs_set_push_clip_rectangle_func (funcs, hb_raster_paint_push_clip_rectangle, nullptr, nullptr);@@ -1944,6 +2162,8 @@ hb_raster_paint_get_extents (const hb_raster_paint_t *paint,* This is equivalent to computing a transformed bounding box in pixel* space and calling hb_raster_paint_set_extents().*+ * The resulting dimensions are capped at 4096 pixels per side.+ ** Return value: `true` if transformed extents are non-empty and set;* `false` otherwise.*@@ -1984,10 +2204,10 @@ hb_raster_paint_set_glyph_extents (hb_raster_paint_t *paint,ty_max = hb_max (ty_max, py[i]);}- int ex0 = (int) floorf (tx_min);- int ey0 = (int) floorf (ty_min);- int ex1 = (int) ceilf (tx_max);- int ey1 = (int) ceilf (ty_max);+ int32_t ex0 = hb_clamp_to<int32_t> (floorf (tx_min));+ int32_t ey0 = hb_clamp_to<int32_t> (floorf (ty_min));+ int32_t ex1 = hb_clamp_to<int32_t> (ceilf (tx_max));+ int32_t ey1 = hb_clamp_to<int32_t> (ceilf (ty_max));if (ex1 <= ex0 || ey1 <= ey0){@@ -1998,8 +2218,8 @@ hb_raster_paint_set_glyph_extents (hb_raster_paint_t *paint,paint->fixed_extents = {ex0, ey0,- (unsigned) (ex1 - ex0),- (unsigned) (ey1 - ey0),+ (unsigned) hb_min ((int64_t) ex1 - ex0, (int64_t) HB_RASTER_MAX_AUTO_DIMENSION),+ (unsigned) hb_min ((int64_t) ey1 - ey0, (int64_t) HB_RASTER_MAX_AUTO_DIMENSION),0};paint->has_extents = true;@@ -2329,6 +2549,7 @@ hb_raster_paint_clear (hb_raster_paint_t *paint){paint->fixed_extents = {};paint->has_extents = false;+ paint->work_left = HB_RASTER_MAX_PAINT_WORK;paint->transform_stack.clear ();paint->release_all_clips ();for (auto *s : paint->surface_stack)diff --git a/thirdparty/harfbuzz/src/hb-raster-paint.hh b/thirdparty/harfbuzz/src/hb-raster-paint.hhindex 7e3e9d0a25d..6f7ebdce8f7 100644--- a/thirdparty/harfbuzz/src/hb-raster-paint.hh+++ b/thirdparty/harfbuzz/src/hb-raster-paint.hh@@ -128,8 +128,23 @@ struct hb_raster_paint_t/* Internal rasterizer for clip-to-glyph */hb_raster_draw_t *clip_rdr = nullptr;+ /* Cumulative work budget for the current paint session; reset by+ * hb_raster_paint_clear(). Bounds total pixel and outline work so+ * that per-node costs cannot multiply with the paint-graph traversal+ * limits of the font tables driving us (e.g. COLR). */+ int64_t work_left = HB_RASTER_MAX_PAINT_WORK;+/* Helpers */+ /* Returns whether the operation should proceed. Allows a single+ * overshoot past zero; callers skip work once the budget is spent. */+ bool charge_work (int64_t work)+ {+ if (unlikely (work_left <= 0)) return false;+ work_left -= work;+ return true;+ }+hb_raster_image_t *acquire_surface (){hb_raster_image_t *img;diff --git a/thirdparty/harfbuzz/src/hb-raster.hh b/thirdparty/harfbuzz/src/hb-raster.hhindex 852aee8445d..a0c08a516dc 100644--- a/thirdparty/harfbuzz/src/hb-raster.hh+++ b/thirdparty/harfbuzz/src/hb-raster.hh@@ -29,6 +29,35 @@#include "hb.hh"+#include "hb-raster.h"++/* Scanline work of the edges accumulated in @draw since the last+ * render/clear: one unit per edge plus its span in rows, clamped to+ * @max_rows per edge. This is what rasterizing the edges costs, as+ * each edge is walked once per row it crosses. Used by the paint+ * layer to charge consumed outline work against its session work+ * budget. */+HB_INTERNAL int64_t+hb_raster_draw_get_edge_work (hb_raster_draw_t *draw, unsigned max_rows);++/* Visibility clip box for curve flattening, in device pixels. Curves+ * whose control-point bounding box falls entirely outside the box are+ * replaced by their chord, which is exact for coverage inside the box.+ * Cleared by hb_raster_draw_clear() (and hence after every render). */+HB_INTERNAL void+hb_raster_draw_set_clip_box (hb_raster_draw_t *draw,+ float x0, float y0,+ float x1, float y1);++/* Points curve-flattening work charges at the caller's session budget+ * (one unit per Bézier subdivision) instead of the standalone+ * per-session HB_RASTER_MAX_DRAW_WORK budget. The rasterizer's local+ * accumulated-edge limit still applies. Cleared by hb_raster_draw_clear()+ * (and hence after every render). */+HB_INTERNAL void+hb_raster_draw_set_external_work (hb_raster_draw_t *draw,+ int64_t *work_left);+/* Shared pixel helpers (used by paint and image compositing). */static HB_ALWAYS_INLINE uint8_tdiff --git a/thirdparty/harfbuzz/src/hb-repacker.hh b/thirdparty/harfbuzz/src/hb-repacker.hhindex b5dfae19960..dbf65c309b3 100644--- a/thirdparty/harfbuzz/src/hb-repacker.hh+++ b/thirdparty/harfbuzz/src/hb-repacker.hh@@ -379,6 +379,17 @@ hb_resolve_graph_overflows (hb_tag_t table_tag,DEBUG_MSG (SUBSET_REPACK, nullptr, "Extensions promotion failed.");return false;}++ // an additional sorting is needed before assign_spaces () which requires+ // correct topological ordering to find space roots+ sorted_graph.sort_shortest_distance_if_needed ();+ if (sorted_graph.in_error ())+ {+ DEBUG_MSG (SUBSET_REPACK, nullptr, "Sorted graph in error state.");+ return false;+ }++ if (!graph::will_overflow (sorted_graph)) return true;}DEBUG_MSG (SUBSET_REPACK, nullptr, "Assigning spaces to 32 bit subgraphs.");diff --git a/thirdparty/harfbuzz/src/hb-script-list.h b/thirdparty/harfbuzz/src/hb-script-list.hindex d500d5ae657..0533275c93f 100644--- a/thirdparty/harfbuzz/src/hb-script-list.h+++ b/thirdparty/harfbuzz/src/hb-script-list.h@@ -492,5 +492,4 @@ typedef enum} hb_script_t;-#endif /* HB_SCRIPT_LIST_H */diff --git a/thirdparty/harfbuzz/src/hb-serialize.hh b/thirdparty/harfbuzz/src/hb-serialize.hhindex 92c79570583..fd91784de51 100644--- a/thirdparty/harfbuzz/src/hb-serialize.hh+++ b/thirdparty/harfbuzz/src/hb-serialize.hh@@ -195,7 +195,7 @@ struct hb_serialize_context_t};}- hb_serialize_context_t (void *start_, unsigned int size) :+ hb_serialize_context_t (void *start_, size_t size) :start ((char *) start_),end (start + size),current (nullptr)@@ -230,7 +230,7 @@ struct hb_serialize_context_t|| errors == HB_SERIALIZE_ERROR_ARRAY_OVERFLOW;}- void reset (void *start_, unsigned int size)+ void reset (void *start_, size_t size){start = (char*) start_;end = start + size;@@ -680,7 +680,7 @@ struct hb_serialize_context_tHB_NODISCARDType *embed (const Type *obj){- unsigned int size = obj->get_size ();+ size_t size = obj->get_size ();Type *ret = this->allocate_size<Type> (size, false);if (unlikely (!ret)) return nullptr;hb_memcpy (ret, obj, size);@@ -733,6 +733,7 @@ struct hb_serialize_context_tType *extend_size (Type *obj, size_t size, bool clear = true){if (unlikely (in_error ())) return nullptr;+ if (unlikely (size >= INT_MAX)) { err (HB_SERIALIZE_ERROR_OTHER); return nullptr; }assert (this->start <= (char *) obj);assert ((char *) obj <= this->head);diff --git a/thirdparty/harfbuzz/src/hb-set.cc b/thirdparty/harfbuzz/src/hb-set.ccindex a9386c5c911..7488546d078 100644--- a/thirdparty/harfbuzz/src/hb-set.cc+++ b/thirdparty/harfbuzz/src/hb-set.cc@@ -357,6 +357,24 @@ hb_set_is_equal (const hb_set_t *set,return set->is_equal (*other);}+/**+ * hb_set_intersects:+ * @set: A set+ * @other: Another set+ *+ * Tests whether @set and @other have any elements in common.+ *+ * Return value: `true` if the two sets intersect, `false` otherwise.+ *+ * Since: 14.4.0+ **/+hb_bool_t+hb_set_intersects (const hb_set_t *set,+ const hb_set_t *other)+{+ return set->intersects (*other);+}+/*** hb_set_hash:* @set: A setdiff --git a/thirdparty/harfbuzz/src/hb-set.h b/thirdparty/harfbuzz/src/hb-set.hindex 192abf6f63e..2f3d670d23a 100644--- a/thirdparty/harfbuzz/src/hb-set.h+++ b/thirdparty/harfbuzz/src/hb-set.h@@ -131,6 +131,10 @@ HB_EXTERN hb_bool_thb_set_is_equal (const hb_set_t *set,const hb_set_t *other);+HB_EXTERN hb_bool_t+hb_set_intersects (const hb_set_t *set,+ const hb_set_t *other);+HB_EXTERN unsigned inthb_set_hash (const hb_set_t *set);diff --git a/thirdparty/harfbuzz/src/hb-set.hh b/thirdparty/harfbuzz/src/hb-set.hhindex 5cd983c0081..b9ef5df2316 100644--- a/thirdparty/harfbuzz/src/hb-set.hh+++ b/thirdparty/harfbuzz/src/hb-set.hh@@ -87,6 +87,7 @@ struct hb_sparseset_tuint32_t hash () const { return s.hash (); }void add (hb_codepoint_t g) { s.add (g); }+ void add_bits (hb_codepoint_t g, uint64_t bits) { s.add_bits (g, bits); }bool add_range (hb_codepoint_t first, hb_codepoint_t last) { return s.add_range (first, last); }template <typename T>@@ -125,6 +126,9 @@ struct hb_sparseset_tbool may_intersect (const hb_sparseset_t &other) const{ return s.may_intersect (other.s); }+ bool intersects (const hb_sparseset_t &other) const+ { return s.intersects (other.s); }+bool intersects (hb_codepoint_t first, hb_codepoint_t last) const{ return s.intersects (first, last); }@@ -137,11 +141,15 @@ struct hb_sparseset_tbool is_subset (const hb_sparseset_t &larger_set) const { return s.is_subset (larger_set.s); }void union_ (const hb_sparseset_t &other) { s.union_ (other.s); }- void intersect (const hb_sparseset_t &other) { s.intersect (other.s); }+ void intersect (const hb_sparseset_t &other,+ hb_vector_t<unsigned> *workspace = nullptr)+ { s.intersect (other.s, workspace); }void subtract (const hb_sparseset_t &other) { s.subtract (other.s); }void symmetric_difference (const hb_sparseset_t &other) { s.symmetric_difference (other.s); }bool next (hb_codepoint_t *codepoint) const { return s.next (codepoint); }+ bool next_bits (hb_codepoint_t *codepoint, uint64_t *bits) const+ { return s.next_bits (codepoint, bits); }bool previous (hb_codepoint_t *codepoint) const { return s.previous (codepoint); }bool next_range (hb_codepoint_t *first, hb_codepoint_t *last) const{ return s.next_range (first, last); }@@ -151,6 +159,7 @@ struct hb_sparseset_t{ return s.next_many (codepoint, out, size); }unsigned int get_population () const { return s.get_population (); }+ bool get_singleton (hb_codepoint_t *codepoint) const { return s.get_singleton (codepoint); }hb_codepoint_t get_min () const { return s.get_min (); }hb_codepoint_t get_max () const { return s.get_max (); }diff --git a/thirdparty/harfbuzz/src/hb-shape-plan.cc b/thirdparty/harfbuzz/src/hb-shape-plan.ccindex 47eb690a746..4b445336542 100644--- a/thirdparty/harfbuzz/src/hb-shape-plan.cc+++ b/thirdparty/harfbuzz/src/hb-shape-plan.cc@@ -52,6 +52,20 @@* Most client programs will not need to deal with shape plans directly.**/+#ifdef HAVE_HARFRUST+extern "C" void _hb_harfrust_shape_plan_destroy_rs (void *data);+#endif++hb_shape_plan_t::~hb_shape_plan_t ()+{+#ifdef HAVE_HARFRUST+ void *data = harfrust_data.get_relaxed ();+ if (data)+ _hb_harfrust_shape_plan_destroy_rs (data);+#endif+ key.fini ();+}+/** hb_shape_plan_key_t@@ -115,6 +129,7 @@ hb_shape_plan_key_t::init (bool copy,else if (0 == strcmp (*shaper_list, #shaper)) \HB_SHAPER_PLAN (shaper);#include "hb-shaper-list.hh"+#undef HB_SHAPER_IMPLEMENT}elsediff --git a/thirdparty/harfbuzz/src/hb-shape-plan.hh b/thirdparty/harfbuzz/src/hb-shape-plan.hhindex 6fc73939b37..3ee63702bb7 100644--- a/thirdparty/harfbuzz/src/hb-shape-plan.hh+++ b/thirdparty/harfbuzz/src/hb-shape-plan.hh@@ -31,7 +31,6 @@#include "hb-shaper.hh"#include "hb-ot-shape.hh"-struct hb_shape_plan_key_t{hb_segment_properties_t props;@@ -64,13 +63,16 @@ struct hb_shape_plan_key_tstruct hb_shape_plan_t{- ~hb_shape_plan_t () { key.fini (); }+ HB_INTERNAL ~hb_shape_plan_t ();hb_object_header_t header;hb_face_t *face_unsafe; /* We don't carry a reference to face. */hb_shape_plan_key_t key;#ifndef HB_NO_OT_SHAPEhb_ot_shape_plan_t ot;#endif+#ifdef HAVE_HARFRUST+ hb_atomic_t<void *> harfrust_data;+#endif};diff --git a/thirdparty/harfbuzz/src/hb-shape.cc b/thirdparty/harfbuzz/src/hb-shape.ccindex 2a8086fdec5..4004044219b 100644--- a/thirdparty/harfbuzz/src/hb-shape.cc+++ b/thirdparty/harfbuzz/src/hb-shape.cc@@ -316,7 +316,7 @@ hb_shape_justify (hb_font_t *font,/* Copy buffer text as we need it so we can shape multiple times. */unsigned text_len = buffer->len;- auto *text_info = (hb_glyph_info_t *) hb_malloc (text_len * sizeof (buffer->info[0]));+ auto *text_info = (hb_glyph_info_t *) hb_malloc2 (text_len, sizeof (buffer->info[0]));if (unlikely (text_len && !text_info))return false;hb_memcpy (text_info, buffer->info, text_len * sizeof (buffer->info[0]));diff --git a/thirdparty/harfbuzz/src/hb-subset-cff-common.hh b/thirdparty/harfbuzz/src/hb-subset-cff-common.hhindex 3140b9ca36f..9f8883a0195 100644--- a/thirdparty/harfbuzz/src/hb-subset-cff-common.hh+++ b/thirdparty/harfbuzz/src/hb-subset-cff-common.hh@@ -334,6 +334,8 @@ struct cs_command_ttypedef hb_vector_t<cs_command_t> *cs_command_vec_t;+struct cff2_instancing_plan_t;+struct flatten_param_t{flatten_param_t (str_buff_t &flatStr_,@@ -346,6 +348,11 @@ struct flatten_param_tbool drop_hints;const hb_subset_plan_t *plan;cs_command_vec_t commands; /* Optional: capture parsed commands for specialization */++ /* CFF2 partial instancing: when set, blends are rewritten against the+ * instanced variation store instead of being copied or flattened. */+ const cff2_instancing_plan_t *instancer = nullptr;+ bool emitted_blend = false;};template <typename ACC, typename ENV, typename OPSET, op_code_t endchar_op=OpCode_Invalid>@@ -438,30 +445,82 @@ struct parsed_cs_str_t : parsed_values_t<parsed_cs_op_t>parsed (false),hint_dropped (false),has_prefix_ (false),- has_calls_ (false)+ has_calls_ (false),+ coalescing_ (false){SUPER::init ();}+ HB_ALWAYS_INLINEvoid add_op (op_code_t op, const byte_str_ref_t& str_ref){- if (!is_parsed ())- SUPER::add_op (op, str_ref);+ if (is_parsed ()) return;+ if (coalescing_)+ {+ /* Do not record individual tokens; only note their boundaries.+ * Bytes are flushed as verbatim segments at call sites and at+ * the end of the string. Only enabled when per-op granularity+ * is not needed later for hint analysis. */+ penultimate_end_ = last_end_;+ last_end_ = str_ref.get_offset ();+ if (unlikely (op == OpCode_return || op == OpCode_endchar))+ flush_segment (str_ref, last_end_);+ return;+ }+ SUPER::add_op (op, str_ref);}void add_call_op (op_code_t op, const byte_str_ref_t& str_ref, unsigned int subr_num){- if (!is_parsed ())+ if (is_parsed ()) return;+ has_calls_ = true;++ if (coalescing_){- has_calls_ = true;+ /* Flush bytes preceding the subroutine-number token, then skip+ * over the number: it is re-encoded with the new bias. */+ flush_segment (str_ref, penultimate_end_);+ opStart = last_end_;+ SUPER::add_op (op, str_ref, {subr_num});+ penultimate_end_ = last_end_ = str_ref.get_offset ();+ return;+ }- /* Pop the subroutine number. */- values.pop ();+ /* Pop the subroutine number. */+ values.pop ();- SUPER::add_op (op, str_ref, {subr_num});+ SUPER::add_op (op, str_ref, {subr_num});+ }++ /* Flush pending bytes [opStart, end) as verbatim segment entries. */+ void flush_segment (const byte_str_ref_t& str_ref, unsigned end)+ {+ unsigned start = opStart;+ if (end <= start) return;+ while (start < end)+ {+ auto arr = str_ref.sub_array (start, hb_min (end - start, 255u));+ if (unlikely (!arr.length)) break;+ parsed_cs_op_t *val = values.push ();+ val->ptr = arr.arrayZ;+ val->length = arr.length;+ start += arr.length;}+ opStart = end;+ }++ /* For coalescing mode: flush any pending bytes through the current+ * position; used where the string ends without an explicit+ * return/endchar op (CFF2). */+ void flush_coalesced (const byte_str_ref_t& str_ref)+ {+ if (coalescing_ && !is_parsed ())+ flush_segment (str_ref, str_ref.get_offset ());}+ void enable_coalescing () { coalescing_ = true; }+ bool is_coalescing () const { return coalescing_; }+void set_prefix (const number_t &num, op_code_t op = OpCode_Invalid){has_prefix_ = true;@@ -525,6 +584,13 @@ struct parsed_cs_str_t : parsed_values_t<parsed_cs_op_t>bool vsindex_dropped : 1;bool has_prefix_ : 1;bool has_calls_ : 1;+ /* Record verbatim byte segments instead of individual tokens,+ * making a separate compact() pass unnecessary; incompatible with+ * hint analysis. */+ bool coalescing_ : 1;+ /* End offsets of the last two tokens seen (coalescing mode). */+ unsigned penultimate_end_ = 0;+ unsigned last_end_ = 0;op_code_t prefix_op_;number_t prefix_num_;@@ -605,14 +671,19 @@ struct subr_subset_param_tparsed_cs_str_vec_t *parsed_local_subrs_,hb_set_t *global_closure_,hb_set_t *local_closure_,- bool drop_hints_) :+ bool drop_hints_,+ bool coalesce_ = false) :current_parsed_str (parsed_charstring_),parsed_charstring (parsed_charstring_),parsed_global_subrs (parsed_global_subrs_),parsed_local_subrs (parsed_local_subrs_),global_closure (global_closure_),local_closure (local_closure_),- drop_hints (drop_hints_) {}+ drop_hints (drop_hints_),+ coalesce (coalesce_)+ {+ if (coalesce) parsed_charstring->enable_coalescing ();+ }parsed_cs_str_t *get_parsed_str_for_context (call_context_t &context){@@ -651,7 +722,10 @@ struct subr_subset_param_telse{if (!parsed_str->is_parsed ())+ {parsed_str->alloc (env.str_ref.total_size ());+ if (coalesce) parsed_str->enable_coalescing ();+ }current_parsed_str = parsed_str;}}@@ -664,6 +738,7 @@ struct subr_subset_param_thb_set_t *global_closure;hb_set_t *local_closure;bool drop_hints;+ bool coalesce;};struct subr_remap_t : hb_inc_bimap_t@@ -781,6 +856,12 @@ struct subr_subsetter_treturn false;}+ /* When hints are not analyzed (not dropping hints, not populating+ * the accelerator), coalesce parsed tokens as they are added,+ * instead of a separate compact() pass. */+ bool coalesce = !(plan->flags & HB_SUBSET_FLAGS_NO_HINTING) &&+ !plan->inprogress_accelerator;+/* phase 1 & 2 */for (auto _ : plan->new_to_old_gid_list){@@ -813,7 +894,8 @@ struct subr_subsetter_t&parsed_local_subrs_storage[fd],&closures.global_closure,&closures.local_closures[fd],- plan->flags & HB_SUBSET_FLAGS_NO_HINTING);+ plan->flags & HB_SUBSET_FLAGS_NO_HINTING,+ coalesce);if (unlikely (!interp.interpret (param)))return false;@@ -845,8 +927,11 @@ struct subr_subsetter_t** The compacting both saves memory and makes further operations* faster.+ *+ * Not needed when tokens were coalesced during parsing.*/- parsed_charstrings[new_glyph].compact ();+ if (!coalesce)+ parsed_charstrings[new_glyph].compact ();}/* Since parsed strings were loaded from accelerator, we still needdiff --git a/thirdparty/harfbuzz/src/hb-subset-cff1.cc b/thirdparty/harfbuzz/src/hb-subset-cff1.ccindex ba71e4cc889..fee2fb933de 100644--- a/thirdparty/harfbuzz/src/hb-subset-cff1.cc+++ b/thirdparty/harfbuzz/src/hb-subset-cff1.cc@@ -518,6 +518,7 @@ struct cff1_subset_planglyph_to_sid_map_t *glyph_to_sid_map = acc.cff_accelerator ?acc.cff_accelerator->glyph_to_sid_map.get_acquire () :nullptr;+bool created_map = false;if (!glyph_to_sid_map && acc.cff_accelerator){@@ -525,11 +526,17 @@ struct cff1_subset_planglyph_to_sid_map = acc.create_glyph_to_sid_map ();}+ if (!glyph_to_sid_map || glyph_to_sid_map->in_error ())+ {+ glyph_to_sid_map = nullptr;+ created_map = false;+ }+auto it = hb_iter (plan->new_to_old_gid_list);if (it->first == 0) it++;auto _ = *it;bool not_is_cid = !acc.is_CID ();- bool skip = !not_is_cid && glyph_to_sid_map;+ bool skip = !not_is_cid && glyph_to_sid_map && !identity_charset;if (not_is_cid)sidmap.alloc (num_glyphs);for (hb_codepoint_t glyph = 1; glyph < num_glyphs; glyph++)@@ -545,12 +552,18 @@ struct cff1_subset_plan/* Retain the SID for the old missing glyph ID */old_glyph = glyph;}- unsigned sid = glyph_to_sid_map ?- glyph_to_sid_map->arrayZ[old_glyph].code :- acc.glyph_to_sid (old_glyph, &glyph_to_sid_cache);+ unsigned sid;+ if (identity_charset)+ sid = glyph;+ else+ {+ sid = glyph_to_sid_map ?+ glyph_to_sid_map->arrayZ[old_glyph].code :+ acc.glyph_to_sid (old_glyph, &glyph_to_sid_cache);- if (not_is_cid)- sid = sidmap.add (sid);+ if (not_is_cid)+ sid = sidmap.add (sid);+ }if (sid != last_sid + 1)subset_charset_ranges.push (code_pair_t {sid, glyph});@@ -621,6 +634,7 @@ struct cff1_subset_planorig_fdcount = acc.fdCount;drop_hints = plan->flags & HB_SUBSET_FLAGS_NO_HINTING;desubroutinize = plan->flags & HB_SUBSET_FLAGS_DESUBROUTINIZE;+ identity_charset = (plan->flags & HB_SUBSET_FLAGS_CFF_IDENTITY_CHARSET) && acc.is_CID ();#ifdef HB_EXPERIMENTAL_APImin_charstrings_off_size = (plan->flags & HB_SUBSET_FLAGS_IFTB_REQUIREMENTS) ? 4 : 0;@@ -628,7 +642,7 @@ struct cff1_subset_planmin_charstrings_off_size = 0;#endif- subset_charset = !acc.is_predef_charset ();+ subset_charset = !acc.is_predef_charset () || identity_charset;if (!subset_charset)/* check whether the subset renumbers any glyph IDs */for (const auto &_ : plan->new_to_old_gid_list)@@ -786,6 +800,7 @@ struct cff1_subset_planunsigned int topDictModSIDs[name_dict_values_t::ValCount];bool desubroutinize = false;+ bool identity_charset = false;unsigned min_charstrings_off_size = 0;};diff --git a/thirdparty/harfbuzz/src/hb-subset-cff2.cc b/thirdparty/harfbuzz/src/hb-subset-cff2.ccindex 262eeb1aba1..6fc62124acc 100644--- a/thirdparty/harfbuzz/src/hb-subset-cff2.cc+++ b/thirdparty/harfbuzz/src/hb-subset-cff2.cc@@ -30,6 +30,7 @@#include "hb-open-type.hh"#include "hb-ot-cff2-table.hh"+#include "hb-ot-var-common.hh"#include "hb-set.h"#include "hb-subset-plan.hh"#include "hb-subset-cff-common.hh"@@ -38,6 +39,353 @@using namespace CFF;+namespace CFF {++/*+ * Partial instancing (some axes pinned or limited, others kept).+ *+ * This is a port of fontTools' instantiateCFF2 (fonttools/fonttools#3506),+ * with one simplification: the variation-store instancing solver acts on+ * regions independently of the per-blend delta values, so instead of lifting+ * every blend's deltas into the store, instancing it, and reading the rows+ * back, we instance each VarData once with identity delta rows. The+ * instantiated tuples then give, per VarData, a fixed linear map from old+ * per-region deltas to new per-region deltas. The contribution that folds+ * into each blend's default value is the old store's region scalars+ * evaluated at the new default location (plan->normalized_coords); the+ * surviving rebased regions all evaluate to zero there.+ *+ * Use: create (), then note_use () for every blend the retained charstrings+ * and private dicts hold, then finalize (); only VarDatas that are both+ * still variable and actually used survive into the new store.+ */+struct cff2_instancing_plan_t+{+ struct vardata_transform_t+ {+ /* new_deltas[j] = Σ_i matrix[j][i] * old_deltas[i] */+ hb_vector_t<hb_vector_t<float>> matrix;+ /* Default-value fold-in scalars, one per old region: the old store's+ * region scalars at the new default location. */+ hb_vector_t<float> gains;+ /* Surviving regions, parallel to matrix rows. */+ hb_vector_t<hb_hashmap_t<hb_tag_t, Triple>> regions;+ /* Index into the new global region list, per new region (finalize). */+ hb_vector_t<unsigned> region_indices;+ unsigned new_major = 0;+ bool alive_ = false;+ bool alive () const { return alive_; }++ /* One value's delta for new region j, from its old per-region deltas. */+ double transform_delta (unsigned j, hb_array_t<const number_t> deltas) const+ {+ const hb_vector_t<float> &col = matrix.arrayZ[j];+ double d = 0.;+ unsigned count = hb_min (col.length, deltas.length);+ for (unsigned c = 0; c < count; c++)+ d += (double) col.arrayZ[c] * deltas.arrayZ[c].to_real ();+ return d;+ }+ };++ hb_vector_t<vardata_transform_t> transforms; /* per old VarData (vsindex) */+ hb_vector_t<hb_hashmap_t<hb_tag_t, Triple>> new_regions; /* global region list */+ hb_set_t used_majors;+ unsigned new_major_count = 0;++ bool has_variations () const { return new_major_count; }++ const vardata_transform_t *get_transform (unsigned major) const+ { return major < transforms.length ? &transforms.arrayZ[major] : nullptr; }++ /* Record that a retained blend references this VarData. */+ void note_use (unsigned major) { used_majors.add (major); }++ /* The new vsindex a private dict's (or charstring's) old ivs maps to;+ * dead VarDatas fall back to 0, their blends having become static. */+ unsigned remap_ivs (unsigned old_ivs) const+ {+ const vardata_transform_t *t = get_transform (old_ivs);+ return (t && t->alive ()) ? t->new_major : 0;+ }++ double fold_deltas (unsigned old_ivs, hb_array_t<const number_t> deltas) const+ {+ const vardata_transform_t *t = get_transform (old_ivs);+ if (unlikely (!t || t->gains.length != deltas.length)) return 0.;+ double v = 0.;+ for (unsigned i = 0; i < deltas.length; i++)+ v += (double) t->gains.arrayZ[i] * deltas.arrayZ[i].to_real ();+ return v;+ }++ bool create (const CFF2ItemVariationStore *cff2VarStore,+ const hb_subset_plan_t *plan)+ {+ const OT::ItemVariationStore &varStore = cff2VarStore->varStore;+ unsigned major_count = varStore.get_sub_table_count ();+ if (!transforms.resize (major_count)) return false;++ if (!varStore.get_region_list ().get_var_regions (plan->axes_old_index_tag_map, orig_regions))+ return false;++ /* Instance each VarData with identity delta rows; the surviving tuples'+ * delta columns are the old-region → new-region transform. */+ OT::optimize_scratch_t scratch;+ for (unsigned m = 0; m < major_count; m++)+ {+ const OT::VarData &var_data = varStore.get_sub_table (m);+ unsigned k = var_data.get_region_index_count ();+ vardata_transform_t &t = transforms.arrayZ[m];++ if (!t.gains.resize_exact (k)) return false;+ varStore.get_region_scalars (m, plan->normalized_coords.arrayZ,+ plan->normalized_coords.length,+ t.gains.arrayZ, k);++ OT::tuple_variations_t tuples;+ for (unsigned r = 0; r < k; r++)+ {+ OT::tuple_delta_t tuple;+ if (!tuple.deltas_x.resize (k) ||+ !tuple.indices.resize (k))+ return false;+ for (unsigned i = 0; i < k; i++)+ tuple.indices.arrayZ[i] = true;+ tuple.deltas_x.arrayZ[r] = 1.f;+ unsigned region_index = var_data.get_region_index (r);+ if (unlikely (region_index >= orig_regions.length)) return false;+ tuple.axis_tuples = orig_regions.arrayZ[region_index];+ if (unlikely (tuple.axis_tuples.in_error ())) return false;+ tuples.tuple_vars.push (std::move (tuple));+ }+ if (unlikely (tuples.tuple_vars.in_error ())) return false;++ if (!tuples.instantiate (plan->axes_location, plan->axes_triple_distances, scratch))+ return false;++ for (auto &tuple : tuples.tuple_vars)+ {+ if (unlikely (tuple.deltas_x.length != k)) return false;+ hb_vector_t<float> col;+ if (unlikely (!col.resize_exact (k))) return false;+ for (unsigned i = 0; i < k; i++)+ col.arrayZ[i] = tuple.deltas_x.arrayZ[i];+ t.matrix.push (std::move (col));+ t.regions.push (std::move (tuple.axis_tuples));+ }+ if (unlikely (t.matrix.in_error () || t.regions.in_error ())) return false;+ }++ return true;+ }++ /* Decide which VarDatas survive, number them, and build the new global+ * region list: surviving original regions first, in their original order,+ * then solver-split new regions in order of appearance (fontTools'+ * rebuildRegions + prune_regions). */+ bool finalize ()+ {+ for (unsigned m = 0; m < transforms.length; m++)+ {+ vardata_transform_t &t = transforms.arrayZ[m];+ t.alive_ = t.matrix.length && used_majors.has (m);+ if (t.alive_)+ t.new_major = new_major_count++;+ }++ /* Keys hash by content, so pointers into different owners compare fine. */+ hb_hashmap_t<const hb_hashmap_t<hb_tag_t, Triple>*, unsigned> region_idx_map;+ hb_vector_t<const hb_hashmap_t<hb_tag_t, Triple>*> region_ptrs;+ for (const vardata_transform_t &t : transforms)+ {+ if (!t.alive ()) continue;+ for (const auto ®ion : t.regions)+ if (!region_idx_map.has (®ion))+ if (unlikely (!region_idx_map.set (®ion, (unsigned) -1)))+ return false;+ }+ for (const auto &r : orig_regions)+ {+ unsigned *idx;+ if (region_idx_map.has (&r, &idx) && *idx == (unsigned) -1)+ {+ if (unlikely (!region_idx_map.set (&r, region_ptrs.length))) return false;+ region_ptrs.push (&r);+ }+ }+ for (const vardata_transform_t &t : transforms)+ {+ if (!t.alive ()) continue;+ for (const auto ®ion : t.regions)+ {+ unsigned *idx;+ if (region_idx_map.has (®ion, &idx) && *idx == (unsigned) -1)+ {+ if (unlikely (!region_idx_map.set (®ion, region_ptrs.length))) return false;+ region_ptrs.push (®ion);+ }+ }+ }+ if (unlikely (region_ptrs.in_error ())) return false;++ for (vardata_transform_t &t : transforms)+ {+ if (!t.alive ()) continue;+ for (const auto ®ion : t.regions)+ {+ unsigned *idx;+ if (unlikely (!region_idx_map.has (®ion, &idx))) return false;+ t.region_indices.push (*idx);+ }+ if (unlikely (t.region_indices.in_error ())) return false;+ }++ if (!new_regions.resize (region_ptrs.length)) return false;+ for (unsigned i = 0; i < region_ptrs.length; i++)+ {+ new_regions.arrayZ[i] = *region_ptrs.arrayZ[i];+ if (unlikely (new_regions.arrayZ[i].in_error ())) return false;+ }++ return true;+ }++ /* Serialize the instanced store: a CFF2ItemVariationStore whose VarDatas+ * carry no items, just region indexes (blend deltas live in charstrings).+ * Laid out manually since all sizes are known up front. */+ bool serialize_var_store (hb_serialize_context_t *c,+ const hb_vector_t<hb_tag_t> &axis_tags) const+ {+ unsigned data_count = new_major_count;+ unsigned header_size = 2 + 4 + 2 + 4 * data_count;++ uint64_t offset = header_size;+ hb_vector_t<unsigned> data_offsets;+ for (const vardata_transform_t &t : transforms)+ {+ if (!t.alive ()) continue;+ data_offsets.push ((unsigned) offset);+ offset += 6 + 2 * (uint64_t) t.region_indices.length;+ }+ if (unlikely (data_offsets.in_error () || data_offsets.length != data_count))+ return false;+ unsigned regions_offset = (unsigned) offset;+ uint64_t total = offset + 4 + (uint64_t) new_regions.length * axis_tags.length * 6;+ if (unlikely (total > 0xFFFFu)) return false;++ HBUINT16 *size_field = c->allocate_size<HBUINT16> (HBUINT16::static_size);+ if (unlikely (!size_field)) return false;+ *size_field = total;++ char *header = c->allocate_size<char> (header_size);+ if (unlikely (!header)) return false;+ * (HBUINT16 *) (header + 0) = 1; /* format */+ * (HBUINT32 *) (header + 2) = regions_offset;+ * (HBUINT16 *) (header + 6) = data_count;+ for (unsigned i = 0; i < data_count; i++)+ * (HBUINT32 *) (header + 8 + 4 * i) = data_offsets.arrayZ[i];++ for (const vardata_transform_t &t : transforms)+ {+ if (!t.alive ()) continue;+ unsigned k = t.region_indices.length;+ HBUINT16 *v = (HBUINT16 *) c->allocate_size<char> (6 + 2 * k);+ if (unlikely (!v)) return false;+ v[0] = 0; /* itemCount */+ v[1] = 0; /* wordSizeCount */+ v[2] = k; /* regionIndices.len */+ for (unsigned j = 0; j < k; j++)+ v[3 + j] = t.region_indices.arrayZ[j];+ }++ hb_vector_t<const hb_hashmap_t<hb_tag_t, Triple>*> region_ptrs;+ if (unlikely (!region_ptrs.alloc_exact (new_regions.length))) return false;+ for (const auto &r : new_regions)+ region_ptrs.push (&r);+ auto *region_list = c->start_embed<OT::VarRegionList> ();+ return region_list->serialize (c, axis_tags, region_ptrs);+ }++ private:+ hb_vector_t<hb_hashmap_t<hb_tag_t, Triple>> orig_regions;+};++/* Usage-collection pass for partial instancing: record which VarDatas the+ * retained charstrings' and private dicts' blends reference. Mirrors the+ * emission pass: blends consumed by dropped hint ops don't count. */+struct cff2_usage_param_t+{+ void init () {}++ cff2_instancing_plan_t *instancing = nullptr;+ bool drop_hints = false;+ unsigned ivs = 0; /* dict-side current vsindex */+};++struct cff2_cs_opset_usage_t : cff2_cs_opset_t<cff2_cs_opset_usage_t, cff2_usage_param_t, blend_arg_t>+{+ static void flush_args_and_op (op_code_t op, cff2_cs_interp_env_t<blend_arg_t> &env, cff2_usage_param_t& param)+ {+ bool counts = true;+ switch (op)+ {+ case OpCode_return:+ case OpCode_endchar:+ counts = false;+ break;++ case OpCode_hstem:+ case OpCode_hstemhm:+ case OpCode_vstem:+ case OpCode_vstemhm:+ case OpCode_hintmask:+ case OpCode_cntrmask:+ if (param.drop_hints)+ counts = false;+ break;++ default:+ break;+ }++ if (counts)+ for (unsigned int i = 0; i < env.argStack.get_count (); i++)+ if (env.argStack[i].blending ())+ {+ param.instancing->note_use (env.get_ivs ());+ break;+ }++ env.clear_args ();+ }+};++struct cff2_private_dict_usage_opset_t : dict_opset_t+{+ static void process_op (op_code_t op, cff2_priv_dict_interp_env_t& env, cff2_usage_param_t& param)+ {+ switch (op) {+ case OpCode_vsindexdict:+ env.process_vsindex ();+ param.ivs = env.get_ivs ();+ env.clear_args ();+ return;+ case OpCode_blenddict:+ param.instancing->note_use (param.ivs);+ env.clear_args ();+ return;+ default:+ dict_opset_t::process_op (op, env);+ if (!env.argStack.is_empty ()) return;+ env.clear_args ();+ return;+ }+ }+};++} /* namespace CFF */+struct cff2_sub_table_info_t : cff_sub_table_info_t{cff2_sub_table_info_t ()@@ -129,6 +477,8 @@ struct cff2_cs_opset_flatten_t : cff2_cs_opset_t<cff2_cs_opset_flatten_t, flattecase OpCode_return:case OpCode_endchar:/* dummy opcodes in CFF2. ignore */+ if (op == OpCode_endchar && param.instancer)+ emit_vsindex_prefix (env, param);break;case OpCode_hstem:@@ -162,7 +512,10 @@ struct cff2_cs_opset_flatten_t : cff2_cs_opset_t<cff2_cs_opset_flatten_t, flatteenv.set_error ();return;}- flatten_blends (arg, i, env, param);+ if (param.instancer)+ rewrite_blends (arg, i, env, param);+ else+ flatten_blends (arg, i, env, param);i += arg.numValues;}else@@ -202,6 +555,113 @@ struct cff2_cs_opset_flatten_t : cff2_cs_opset_t<cff2_cs_opset_flatten_t, flatteencoder.encode_op (OpCode_blendcs);}+ /* Partial instancing: rewrite one blend group against the instanced store.+ * Each value's default absorbs the folded (pinned-away) contribution, and+ * its deltas are mapped onto the new region list. */+ static void rewrite_blends (const blend_arg_t &arg, unsigned int i, cff2_cs_interp_env_t<blend_arg_t> &env, flatten_param_t& param)+ {+ const cff2_instancing_plan_t &instancer = *param.instancer;+ unsigned ivs = env.get_ivs ();+ const cff2_instancing_plan_t::vardata_transform_t *t = instancer.get_transform (ivs);+ if (unlikely (!t))+ {+ env.set_error ();+ return;+ }++ unsigned n = arg.numValues;+ for (unsigned int j = 0; j < n; j++)+ {+ const blend_arg_t &arg1 = env.argStack[i + j];+ if (unlikely (!(arg1.blending () && (arg1.numValues == n) && (arg1.valueIndex == j) &&+ (arg1.deltas.length == env.get_region_count ()) &&+ (arg1.deltas.length == t->gains.length))))+ {+ env.set_error ();+ return;+ }+ }++ str_encoder_t encoder (param.flatStr);+ unsigned k_new = t->alive () ? t->matrix.length : 0;++ if (!k_new)+ {+ /* All of this VarData's regions died; blends dissolve into statics. */+ for (unsigned int j = 0; j < n; j++)+ {+ const blend_arg_t &arg1 = env.argStack[i + j];+ number_t v;+ v.set_real (arg1.to_real () + round (instancer.fold_deltas (ivs, arg1.deltas.as_array ())));+ encoder.encode_num_cs (v);+ }+ return;+ }++ /* Emit in chunks so the output charstring stays within the argument+ * stack limit: values already emitted for this op, plus this chunk's+ * defaults, deltas and count, must not exceed 513. */+ unsigned done = 0;+ while (done < n)+ {+ unsigned avail = 512 > (i + done) ? 512 - (i + done) : 0;+ unsigned chunk = hb_min (avail / (k_new + 1), n - done);+ if (unlikely (!chunk))+ {+ env.set_error ();+ return;+ }++ for (unsigned int j = done; j < done + chunk; j++)+ {+ const blend_arg_t &arg1 = env.argStack[i + j];+ number_t v;+ v.set_real (arg1.to_real () + round (instancer.fold_deltas (ivs, arg1.deltas.as_array ())));+ encoder.encode_num_cs (v);+ }+ for (unsigned int j = done; j < done + chunk; j++)+ {+ const blend_arg_t &arg1 = env.argStack[i + j];+ for (unsigned r = 0; r < k_new; r++)+ {+ number_t v;+ v.set_int ((int) round (t->transform_delta (r, arg1.deltas.as_array ())));+ encoder.encode_num_cs (v);+ }+ }+ encoder.encode_int (chunk);+ encoder.encode_op (OpCode_blendcs);+ done += chunk;+ }+ param.emitted_blend = true;+ }++ /* Partial instancing: prepend a vsindex op when the charstring's+ * (remapped) ivs differs from its FD's (remapped) private-dict ivs. */+ static void emit_vsindex_prefix (cff2_cs_interp_env_t<blend_arg_t> &env, flatten_param_t& param)+ {+ if (!param.emitted_blend) return;+ const cff2_instancing_plan_t &instancer = *param.instancer;+ unsigned new_ivs = instancer.remap_ivs (env.get_ivs ());+ unsigned fd_ivs = instancer.remap_ivs (env.get_orig_ivs ());+ if (new_ivs == fd_ivs) return;++ str_buff_t prefix;+ str_encoder_t enc (prefix);+ enc.encode_int ((int) new_ivs);+ enc.encode_op (OpCode_vsindexcs);++ str_buff_t &buf = param.flatStr;+ unsigned old_len = buf.length;+ if (unlikely (prefix.in_error () || !buf.resize (old_len + prefix.length)))+ {+ env.set_error ();+ return;+ }+ memmove (buf.arrayZ + prefix.length, buf.arrayZ, old_len);+ hb_memcpy (buf.arrayZ, prefix.arrayZ, prefix.length);+ }+static void flush_op (op_code_t op, cff2_cs_interp_env_t<blend_arg_t> &env, flatten_param_t& param){switch (op)@@ -254,12 +714,14 @@ struct cff2_cs_opset_subr_subset_t : cff2_cs_opset_t<cff2_cs_opset_subr_subset_tswitch (op) {case OpCode_return:+ param.current_parsed_str->flush_coalesced (env.str_ref);param.current_parsed_str->set_parsed ();env.return_from_subr ();param.set_current_str (env, false);break;case OpCode_endchar:+ param.current_parsed_str->flush_coalesced (env.str_ref);param.current_parsed_str->set_parsed ();SUPER::process_op (op, env, param);break;@@ -326,7 +788,12 @@ struct cff2_private_blend_encoder_param_tif (!seen_blend){region_count = varStore->varStore.get_region_index_count (ivs);- scalars.resize_exact (region_count);+ if (unlikely (!scalars.resize_exact (region_count)))+ {+ if (c) c->err (HB_SERIALIZE_ERROR_OTHER);+ seen_blend = true;+ return;+ }varStore->varStore.get_region_scalars (ivs, normalized_coords.arrayZ, normalized_coords.length,&scalars[0], region_count);seen_blend = true;@@ -353,6 +820,13 @@ struct cff2_private_blend_encoder_param_thb_vector_t<float> scalars;const CFF2ItemVariationStore *varStore = nullptr;hb_array_t<int> normalized_coords;++ /* CFF2 partial instancing: when set, blends are rewritten against the+ * instanced variation store instead of being flattened. */+ const cff2_instancing_plan_t *instancer = nullptr;+ /* Error-compensated fold rounding state, per dict operator. */+ double fold_exact = 0.;+ double fold_emitted = 0.;};struct cff2_private_dict_blend_opset_t : dict_opset_t@@ -365,6 +839,98 @@ struct cff2_private_dict_blend_opset_t : dict_opset_targ.set_int (round (arg.to_real () + param.blend_deltas (blends)));}+ /* The fold added to a value, error-compensated across the operator: most+ * blended private-dict values (BlueValues, StemSnap*, ...) are+ * delta-encoded, so independently rounded folds would accumulate in the+ * decoded absolutes; keeping the emitted cumulative fold equal to the+ * rounded exact cumulative fold bounds every absolute within ±0.5. */+ static double fold (cff2_private_blend_encoder_param_t& param,+ const hb_array_t<const number_t> blends)+ {+ double f = param.blend_deltas (blends);+ double emit = round (param.fold_exact + f) - param.fold_emitted;+ param.fold_exact += f;+ param.fold_emitted += emit;+ return emit;+ }++ /* Partial instancing: emit the args preceding this blend group, then the+ * group itself rewritten against the instanced store, and clear the+ * stack. The op's remaining args are flushed at process_op time. */+ static void rewrite_blends (cff2_priv_dict_interp_env_t& env,+ cff2_private_blend_encoder_param_t& param,+ unsigned start, unsigned n, unsigned k)+ {+ const cff2_instancing_plan_t &instancer = *param.instancer;+ const cff2_instancing_plan_t::vardata_transform_t *t = instancer.get_transform (param.ivs);+ if (unlikely (!t || t->gains.length != k))+ {+ env.set_error ();+ return;+ }++ str_buff_t str;+ str_encoder_t encoder (str);++ for (unsigned idx = 0; idx < start; idx++)+ encoder.encode_num_tp (env.argStack[idx]);++ unsigned k_new = t->alive () ? t->matrix.length : 0;+ if (!k_new)+ {+ /* This VarData died (or is unused by any retained charstring, which+ * can happen for FDs kept only for retain-gids holes); blends+ * dissolve into statics. */+ for (unsigned j = 0; j < n; j++)+ {+ const hb_array_t<const number_t> blends = env.argStack.sub_array (start + n + (j * k), k);+ number_t v;+ v.set_real (env.argStack[start + j].to_real () + fold (param, blends));+ encoder.encode_num_tp (v);+ }+ }+ else+ {+ unsigned done = 0;+ while (done < n)+ {+ unsigned avail = 512 > (start + done) ? 512 - (start + done) : 0;+ unsigned chunk = hb_min (avail / (k_new + 1), n - done);+ if (unlikely (!chunk))+ {+ env.set_error ();+ return;+ }++ for (unsigned j = done; j < done + chunk; j++)+ {+ const hb_array_t<const number_t> blends = env.argStack.sub_array (start + n + (j * k), k);+ number_t v;+ v.set_real (env.argStack[start + j].to_real () + fold (param, blends));+ encoder.encode_num_tp (v);+ }+ for (unsigned j = done; j < done + chunk; j++)+ {+ const hb_array_t<const number_t> blends = env.argStack.sub_array (start + n + (j * k), k);+ for (unsigned r = 0; r < k_new; r++)+ {+ number_t v;+ v.set_int ((int) round (t->transform_delta (r, blends)));+ encoder.encode_num_tp (v);+ }+ }+ encoder.encode_int (chunk);+ encoder.encode_op (OpCode_blenddict);+ done += chunk;+ }+ }++ auto bytes = str.as_bytes ();+ param.c->embed (&bytes, bytes.length);++ env.clear_args ();+ }+static void process_blend (cff2_priv_dict_interp_env_t& env, cff2_private_blend_encoder_param_t& param){unsigned int n, k;@@ -372,14 +938,30 @@ struct cff2_private_dict_blend_opset_t : dict_opset_tparam.process_blend ();k = param.region_count;n = env.argStack.pop_uint ();++ unsigned count = env.argStack.get_count ();+ unsigned int total;+ if (unlikely (hb_unsigned_mul_overflows (k + 1, n, &total) || total > count))+ {+ env.set_error ();+ return;+ }+/* copy the blend values into blend array of the default values */- unsigned int start = env.argStack.get_count () - ((k+1) * n);+ unsigned int start = count - total;/* let an obvious error case fail, but note CFF2 spec doesn't forbid n==0 */- if (unlikely (start > env.argStack.get_count ()))+ if (unlikely (start > count)){env.set_error ();return;}++ if (param.instancer && k)+ {+ rewrite_blends (env, param, start, n, k);+ return;+ }+for (unsigned int i = 0; i < n; i++){const hb_array_t<const number_t> blends = env.argStack.sub_array (start + n + (i * k), k);@@ -410,6 +992,20 @@ struct cff2_private_dict_blend_opset_t : dict_opset_tcase OpCode_vsindexdict:env.process_vsindex ();param.ivs = env.get_ivs ();+ if (param.instancer)+ {+ /* Re-emit with the remapped vsindex; 0 is the dict default. */+ unsigned new_ivs = param.instancer->remap_ivs (param.ivs);+ if (new_ivs)+ {+ str_buff_t str;+ str_encoder_t encoder (str);+ encoder.encode_int ((int) new_ivs);+ encoder.encode_op (OpCode_vsindexdict);+ auto bytes = str.as_bytes ();+ param.c->embed (&bytes, bytes.length);+ }+ }env.clear_args ();return;case OpCode_blenddict:@@ -439,6 +1035,7 @@ struct cff2_private_dict_blend_opset_t : dict_opset_tparam.c->embed (&bytes, bytes.length);env.clear_args ();+ param.fold_exact = param.fold_emitted = 0.;}};@@ -446,9 +1043,11 @@ struct cff2_private_dict_op_serializer_t : op_serializer_t{cff2_private_dict_op_serializer_t (bool desubroutinize_, bool drop_hints_, bool pinned_,const CFF::CFF2ItemVariationStore* varStore_,- hb_array_t<int> normalized_coords_)+ hb_array_t<int> normalized_coords_,+ const cff2_instancing_plan_t *instancer_ = nullptr): desubroutinize (desubroutinize_), drop_hints (drop_hints_), pinned (pinned_),- varStore (varStore_), normalized_coords (normalized_coords_) {}+ param (nullptr, varStore_, normalized_coords_)+ { param.instancer = instancer_; }bool serialize (hb_serialize_context_t *c,const op_str_t &opstr,@@ -467,11 +1066,13 @@ struct cff2_private_dict_op_serializer_t : op_serializer_treturn_trace (FontDict::serialize_link2_op (c, opstr.op, subrs_link));}- if (pinned)+ if (pinned || param.instancer){- // Reinterpret opstr and process blends.+ /* Reinterpret opstr and process blends. The param persists across+ * this dict's opstrs, so that an ivs set by a vsindexdict opstr is+ * still in effect when a later opstr's blends are processed. */cff2_priv_dict_interp_env_t env {hb_ubytes_t (opstr.ptr, opstr.length)};- cff2_private_blend_encoder_param_t param (c, varStore, normalized_coords);+ param.c = c;dict_interpreter_t<cff2_private_dict_blend_opset_t, cff2_private_blend_encoder_param_t, cff2_priv_dict_interp_env_t> interp (env);return_trace (interp.interpret (param));}@@ -483,11 +1084,11 @@ struct cff2_private_dict_op_serializer_t : op_serializer_tconst bool desubroutinize;const bool drop_hints;const bool pinned;- const CFF::CFF2ItemVariationStore* varStore;- hb_array_t<int> normalized_coords;+ mutable cff2_private_blend_encoder_param_t param;};+namespace OT {struct cff2_subset_plan{@@ -502,12 +1103,21 @@ struct cff2_subset_planorig_fdcount = acc.fdArray->count;drop_hints = plan->flags & HB_SUBSET_FLAGS_NO_HINTING;- pinned = (bool) plan->normalized_coords;+ bool instancing_requested = (bool) plan->normalized_coords;+ pinned = instancing_requested && plan->all_axes_pinned;normalized_coords = plan->normalized_coords;head_maxp_info = plan->head_maxp_info;hmtx_map = &plan->hmtx_map;desubroutinize = plan->flags & HB_SUBSET_FLAGS_DESUBROUTINIZE ||- pinned; // For instancing we need this path+ instancing_requested; // For instancing we need this path++ /* Partial instancing: some axes pinned or limited, others kept. */+ partial_instancing = instancing_requested && !pinned &&+ acc.varStore != &Null (CFF2ItemVariationStore);+ if (partial_instancing &&+ unlikely (!instancing.create (acc.varStore, plan)))+ return false;+ axis_tags = &plan->axis_tags;/* Enable command capture for CFF2→CFF1 conversion (for specialization) */capture_commands = pinned;@@ -520,6 +1130,77 @@ struct cff2_subset_planif (desubroutinize){+ if (partial_instancing)+ {+ /* Pass 1: collect which VarDatas the retained blends reference, so+ * unused ones get pruned and the survivors renumbered. */+ hb_set_t used_fds;+ for (unsigned int i = 0; i < num_glyphs; i++)+ {+ hb_codepoint_t glyph;+ if (!plan->old_gid_for_new_gid (i, &glyph))+ continue;+ const hb_ubytes_t str = (*acc.charStrings)[glyph];+ unsigned int fd = acc.fdSelect->get_fd (glyph);+ if (unlikely (fd >= acc.fdCount))+ return false;+ used_fds.add (fd);++ cff2_cs_interp_env_t<blend_arg_t> env (str, acc, fd);+ cs_interpreter_t<cff2_cs_interp_env_t<blend_arg_t>, cff2_cs_opset_usage_t, cff2_usage_param_t> interp (env);+ cff2_usage_param_t param;+ param.instancing = &instancing;+ param.drop_hints = drop_hints;+ if (unlikely (!interp.interpret (param)))+ return false;+ }+ for (unsigned fd : used_fds)+ {+ cff2_usage_param_t param;+ param.instancing = &instancing;+ unsigned count = acc.privateDicts[fd].get_count ();+ for (unsigned j = 0; j < count; j++)+ {+ const op_str_t &opstr = acc.privateDicts[fd][j];+ if (drop_hints && dict_opset_t::is_hint_op (opstr.op))+ continue;+ cff2_priv_dict_interp_env_t env {hb_ubytes_t (opstr.ptr, opstr.length)};+ dict_interpreter_t<cff2_private_dict_usage_opset_t, cff2_usage_param_t, cff2_priv_dict_interp_env_t> interp (env);+ if (unlikely (!interp.interpret (param)))+ return false;+ }+ }+ if (unlikely (!instancing.finalize ()))+ return false;++ /* Pass 2: like subr_flattener_t, but blends stay symbolic (no coords+ * fed to the env) and get rewritten against the instanced store. */+ if (!subset_charstrings.resize_exact (num_glyphs))+ return false;+ for (unsigned int i = 0; i < num_glyphs; i++)+ {+ hb_codepoint_t glyph;+ if (!plan->old_gid_for_new_gid (i, &glyph))+ continue;+ const hb_ubytes_t str = (*acc.charStrings)[glyph];+ unsigned int fd = acc.fdSelect->get_fd (glyph);+ if (unlikely (fd >= acc.fdCount))+ return false;++ cff2_cs_interp_env_t<blend_arg_t> env (str, acc, fd);+ cs_interpreter_t<cff2_cs_interp_env_t<blend_arg_t>, cff2_cs_opset_flatten_t, flatten_param_t> interp (env);+ flatten_param_t param = {+ subset_charstrings.arrayZ[i],+ (bool) (plan->flags & HB_SUBSET_FLAGS_NO_HINTING),+ plan+ };+ param.instancer = &instancing;+ if (unlikely (!interp.interpret (param)))+ return false;+ }+ }+ else+ {/* Flatten global & local subrs */subr_flattener_t<const OT::cff2::accelerator_subset_t, cff2_cs_interp_env_t<blend_arg_t>, cff2_cs_opset_flatten_t>flattener(acc, plan);@@ -538,6 +1219,7 @@ struct cff2_subset_planif (!flattener.flatten (subset_charstrings))return false;}+ }}else{@@ -603,6 +1285,10 @@ struct cff2_subset_planbool drop_hints = false;bool desubroutinize = false;+ bool partial_instancing = false;+ cff2_instancing_plan_t instancing;+ const hb_vector_t<hb_tag_t> *axis_tags = nullptr;+unsigned min_charstrings_off_size = 0;hb_array_t<int> normalized_coords; // For instantiation@@ -1138,7 +1824,8 @@ OT::cff2::accelerator_subset_t::serialize (hb_serialize_context_t *c,}auto *pd = c->push<PrivateDict> ();cff2_private_dict_op_serializer_t privSzr (plan.desubroutinize, plan.drop_hints, plan.pinned,- varStore, normalized_coords);+ varStore, normalized_coords,+ plan.partial_instancing ? &plan.instancing : nullptr);if (likely (pd->serialize (c, privateDicts[i], privSzr, subrs_link))){unsigned fd = plan.fdmap[i];@@ -1191,13 +1878,30 @@ OT::cff2::accelerator_subset_t::serialize (hb_serialize_context_t *c,if (varStore != &Null (CFF2ItemVariationStore) &&!plan.pinned){- auto *dest = c->push<CFF2ItemVariationStore> ();- if (unlikely (!dest->serialize (c, varStore)))+ if (plan.partial_instancing){- c->pop_discard ();- return false;+ if (plan.instancing.has_variations ())+ {+ c->push ();+ if (unlikely (!plan.instancing.serialize_var_store (c, *plan.axis_tags)))+ {+ c->pop_discard ();+ return false;+ }+ plan.info.var_store_link = c->pop_pack (false);+ }+ /* else: the store emptied; the vstore op gets dropped along with it. */+ }+ else+ {+ auto *dest = c->push<CFF2ItemVariationStore> ();+ if (unlikely (!dest->serialize (c, varStore)))+ {+ c->pop_discard ();+ return false;+ }+ plan.info.var_store_link = c->pop_pack (false);}- plan.info.var_store_link = c->pop_pack (false);}OT::cff2 *cff2 = c->allocate_min<OT::cff2> ();diff --git a/thirdparty/harfbuzz/src/hb-subset-depend.h b/thirdparty/harfbuzz/src/hb-subset-depend.hnew file mode 100644index 00000000000..9d784fc6258--- /dev/null+++ b/thirdparty/harfbuzz/src/hb-subset-depend.h@@ -0,0 +1,133 @@+/*+ * Copyright © 2024 Adobe, Inc.+ *+ * 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.+ *+ * Adobe Author(s): Skef Iterum+ */++#ifndef HB_SUBSET_DEPEND_H+#define HB_SUBSET_DEPEND_H++#if !defined(HB_SUBSET_H_IN) && !defined(HB_NO_SINGLE_HEADER_ERROR)+#error "Include <hb-subset.h> instead."+#endif++#include "hb.h"++HB_BEGIN_DECLS++/**+ * hb_subset_depend_edge_flags_t:+ * @HB_SUBSET_DEPEND_EDGE_FLAG_NONE: No flags set.+ * @HB_SUBSET_DEPEND_EDGE_FLAG_FROM_CONTEXT_POSITION: Edge from a multi-position+ * contextual rule (Context or ChainContext with inputCount > 1). Depend+ * extraction records edges based on what glyphs could statically be at each+ * position according to input coverage or class. However, at runtime lookups+ * within the rule are applied sequentially: a lookup at an earlier position+ * may transform the glyph at a later position, and two lookups at the same+ * position may interact such that one produces a glyph that another+ * immediately consumes as an "intermediate". A glyph that matches the static+ * coverage may therefore not persist at that position when the rule actually+ * fires, so this edge may not trigger during closure.+ * @HB_SUBSET_DEPEND_EDGE_FLAG_FROM_NESTED_CONTEXT: Edge from a lookup invoked+ * within another contextual lookup. The outer context's requirements are not+ * propagated to this edge, so the edge may fire even when those requirements+ * are not met.+ *+ * Flags on dependency edges returned by hb_subset_depend_lookup_glyph() that+ * mark edges which may produce expected over-approximation when computing+ * closure via the depend graph, relative to+ * hb_ot_layout_lookups_substitute_closure(). These flags help distinguish+ * known limitations of static dependency analysis (expected over-approximation)+ * from bugs (unexpected over-approximation).+ *+ * Since: 14.3.0+ */+typedef enum { /*< flags >*/+ HB_SUBSET_DEPEND_EDGE_FLAG_NONE = 0x00u,+ HB_SUBSET_DEPEND_EDGE_FLAG_FROM_CONTEXT_POSITION = 0x01u,+ HB_SUBSET_DEPEND_EDGE_FLAG_FROM_NESTED_CONTEXT = 0x02u,+} hb_subset_depend_edge_flags_t;+#define HB_SUBSET_DEPEND_EDGE_FLAGS_T_DEFINED+/* HB_MARK_AS_FLAG_T is applied in hb-depend-data.hh (internal header only) */++#ifndef HB_NO_SUBSET_DEPEND++/**+ * hb_subset_depend_t:+ *+ * Data type for holding glyph dependency graphs.+ *+ * <warning>Highly experimental API. Subject to change.</warning>+ *+ * Since: 14.3.0+ */+typedef struct hb_subset_depend_t hb_subset_depend_t;++/**+ * hb_subset_depend_entry_t:+ * @table_tag: Source table (e.g. GSUB, glyf, CFF, COLR, MATH).+ * @dependent: Target glyph ID.+ * @layout_tag: Feature tag for GSUB edges; 0 otherwise.+ * @ligature_set_index: Index into the sets array for ligature component+ * glyphs, or #HB_CODEPOINT_INVALID if not a ligature edge.+ * @context_set_index: Index into the sets array for context requirement+ * glyphs, or #HB_CODEPOINT_INVALID if none. Use hb_subset_depend_lookup_set()+ * to retrieve the set.+ * @flags: Edge flags (#hb_subset_depend_edge_flags_t).+ *+ * A single dependency edge returned by hb_subset_depend_lookup_glyph().+ *+ * Since: 14.3.0+ */+typedef struct {+ hb_tag_t table_tag;+ hb_codepoint_t dependent;+ hb_tag_t layout_tag;+ hb_codepoint_t ligature_set_index;+ hb_codepoint_t context_set_index;+ hb_subset_depend_edge_flags_t flags;+} hb_subset_depend_entry_t;++HB_EXTERN hb_subset_depend_t *+hb_subset_depend_from_face_or_fail (hb_face_t *face);++HB_EXTERN unsigned int+hb_subset_depend_lookup_glyph (hb_subset_depend_t *depend,+ hb_codepoint_t gid,+ unsigned int start_offset,+ unsigned int *entry_count, /* IN/OUT */+ hb_subset_depend_entry_t *entries /* OUT */);++HB_EXTERN hb_bool_t+hb_subset_depend_lookup_set (hb_subset_depend_t *depend,+ hb_codepoint_t index,+ hb_set_t *out /* OUT */);++HB_EXTERN void+hb_subset_depend_destroy (hb_subset_depend_t *depend);++#endif++HB_END_DECLS++#endif /* HB_SUBSET_DEPEND_H */diff --git a/thirdparty/harfbuzz/src/hb-subset-input.cc b/thirdparty/harfbuzz/src/hb-subset-input.ccindex a3c3b929562..c3906fdc134 100644--- a/thirdparty/harfbuzz/src/hb-subset-input.cc+++ b/thirdparty/harfbuzz/src/hb-subset-input.cc@@ -128,6 +128,7 @@ hb_subset_input_t::hb_subset_input_t ()HB_TAG ('v', 'c', 'h', 'w'),HB_TAG ('h', 'a', 'l', 't'),HB_TAG ('v', 'h', 'a', 'l'),+ HB_TAG ('p', 'a', 'l', 't'),//privateHB_TAG ('H', 'a', 'r', 'f'),@@ -425,8 +426,7 @@ hb_subset_input_keep_everything (hb_subset_input_t *input)** Pin all axes to default locations in the given subset input object.*- * All axes in a font must be pinned. Additionally, `CFF2` table, if present,- * will be de-subroutinized.+ * The `CFF2` table, if present, will be de-subroutinized.** Return value: `true` if success, `false` otherwise*@@ -466,8 +466,7 @@ hb_subset_input_pin_all_axes_to_default (hb_subset_input_t *input,** Pin an axis to its default location in the given subset input object.*- * All axes in a font must be pinned. Additionally, `CFF2` table, if present,- * will be de-subroutinized.+ * The `CFF2` table, if present, will be de-subroutinized.** Return value: `true` if success, `false` otherwise*@@ -495,8 +494,7 @@ hb_subset_input_pin_axis_to_default (hb_subset_input_t *input,** Pin an axis to a fixed location in the given subset input object.*- * All axes in a font must be pinned. Additionally, `CFF2` table, if present,- * will be de-subroutinized.+ * The `CFF2` table, if present, will be de-subroutinized.** Return value: `true` if success, `false` otherwise*@@ -736,6 +734,374 @@ hb_subset_axis_range_to_string (hb_subset_input_t *input,}#endif+#ifdef HB_EXPERIMENTAL_API+static void+_append_arg (hb_vector_t<char> &sb, const char *arg)+{+ if (sb.in_error ()) return;+ if (sb.length)+ sb.push (' ');+ unsigned len = strlen (arg);+ sb.extend (hb_bytes_t (arg, len));+}+static void+_format_number_set (const hb_set_t *set, hb_vector_t<char> &out, unsigned base = 10)+{+ assert (base == 10 || base == 16);+ if (unlikely (base != 10 && base != 16)) return;++ hb_codepoint_t first = HB_SET_VALUE_INVALID, last = HB_SET_VALUE_INVALID;+ bool first_range = true;+ while (hb_set_next_range (set, &first, &last))+ {+ if (!first_range)+ out.push (',');+ first_range = false;++ char buf[64];+ int len;+ if (first == last)+ {+ if (base == 16)+ len = snprintf (buf, sizeof (buf), "%X", first);+ else+ len = snprintf (buf, sizeof (buf), "%u", first);+ }+ else+ {+ if (base == 16)+ len = snprintf (buf, sizeof (buf), "%X-%X", first, last);+ else+ len = snprintf (buf, sizeof (buf), "%u-%u", first, last);+ }+ if (unlikely (len < 0 || (size_t) len >= sizeof (buf))) return;+ out.extend (hb_bytes_t (buf, len));+ }+}++static void+_format_tag (hb_tag_t tag, hb_vector_t<char> &out)+{+ char buf[4];+ hb_tag_to_string (tag, buf);++ unsigned len = 4;+ while (len > 0 && buf[len - 1] == ' ')+ len--;++ for (unsigned i = 0; i < len; i++)+ {+ char c = buf[i];+ if (!((c >= 'a' && c <= 'z') ||+ (c >= 'A' && c <= 'Z') ||+ (c >= '0' && c <= '9') ||+ c == '-' || c == '_'))+ {+ c = '_';+ }+ out.push (c);+ }+}++static void+_format_tag_set (const hb_set_t *set, hb_vector_t<char> &out)+{+ bool first_tag = true;+ for (hb_codepoint_t tag : *set)+ {+ if (!first_tag)+ out.push (',');+ first_tag = false;++ _format_tag (tag, out);+ }+}++static bool+_is_set_default (const hb_set_t *set, const hb_set_t *default_set)+{+ return hb_set_is_inverted (set) == hb_set_is_inverted (default_set) &&+ hb_set_is_equal (set, default_set);+}++template <typename Formatter>+static void+_format_set_arg (const hb_set_t *set,+ const char *opt_name,+ Formatter &&formatter,+ hb_vector_t<char> &sb)+{+ if (hb_set_is_inverted (set))+ {+ hb_set_t *excluded = hb_set_copy (set);+ hb_set_invert (excluded);++ hb_vector_t<char> opt;+ opt.extend (hb_bytes_t ("--", 2));+ opt.extend (hb_bytes_t (opt_name, strlen (opt_name)));+ opt.extend (hb_bytes_t ("=*", 2));+ opt.push ('\0');+ if (opt.arrayZ) _append_arg (sb, opt.arrayZ);++ if (!hb_set_is_empty (excluded))+ {+ hb_vector_t<char> formatted;+ formatter (excluded, formatted);+ if (formatted.length)+ {+ hb_vector_t<char> opt2;+ opt2.extend (hb_bytes_t ("--", 2));+ opt2.extend (hb_bytes_t (opt_name, strlen (opt_name)));+ opt2.extend (hb_bytes_t ("-=", 2));+ opt2.extend (formatted.as_array ());+ opt2.push ('\0');+ if (opt2.arrayZ) _append_arg (sb, opt2.arrayZ);+ }+ }+ hb_set_destroy (excluded);+ }+ else if (hb_set_is_empty (set))+ {+ hb_vector_t<char> opt;+ opt.extend (hb_bytes_t ("--", 2));+ opt.extend (hb_bytes_t (opt_name, strlen (opt_name)));+ opt.extend (hb_bytes_t ("-=*", 3));+ opt.push ('\0');+ if (opt.arrayZ) _append_arg (sb, opt.arrayZ);+ }+ else+ {+ hb_vector_t<char> formatted;+ formatter (set, formatted);+ if (formatted.length)+ {+ hb_vector_t<char> opt;+ opt.extend (hb_bytes_t ("--", 2));+ opt.extend (hb_bytes_t (opt_name, strlen (opt_name)));+ opt.extend (hb_bytes_t ("=", 1));+ opt.extend (formatted.as_array ());+ opt.push ('\0');+ if (opt.arrayZ) _append_arg (sb, opt.arrayZ);+ }+ }+}++static void+_format_number_set_arg (const hb_set_t *set,+ const char *opt_name,+ hb_vector_t<char> &sb,+ unsigned base = 10)+{+ _format_set_arg (set, opt_name, [base] (const hb_set_t *s, hb_vector_t<char> &out) {+ _format_number_set (s, out, base);+ }, sb);+}++static void+_format_tag_set_arg (const hb_set_t *set,+ const char *opt_name,+ hb_vector_t<char> &sb)+{+ _format_set_arg (set, opt_name, _format_tag_set, sb);+}++static bool+_format_glyph_map_arg (const hb_map_t &glyph_map,+ hb_vector_t<char> &sb)+{+ if (glyph_map.is_empty ())+ return true;++ hb_set_t keys;+ hb_map_keys (&glyph_map, &keys);+ hb_vector_t<char> pairs;+ bool first = true;+ for (hb_codepoint_t key : keys)+ {+ if (!first)+ pairs.push (',');+ first = false;+ hb_codepoint_t val = hb_map_get (&glyph_map, key);+ char buf[64];+ int len = snprintf (buf, sizeof (buf), "%u:%u", key, val);+ if (unlikely (len < 0 || (size_t) len >= sizeof (buf))) return false;+ pairs.extend (hb_bytes_t (buf, len));+ }+ if (pairs.length)+ {+ hb_vector_t<char> opt;+ opt.extend (hb_bytes_t ("--gid-map=", 10));+ opt.extend (pairs.as_array ());+ opt.push ('\0');+ if (opt.arrayZ) _append_arg (sb, opt.arrayZ);+ }+ return true;+}++static bool+_format_axes_location_arg (const hb_hashmap_t<hb_tag_t, Triple> &axes_location,+ hb_vector_t<char> &sb)+{+ if (axes_location.is_empty ())+ return true;++ hb_vector_t<hb_tag_t> axis_tags;+ for (auto tag : axes_location.keys ())+ axis_tags.push (tag);+ axis_tags.qsort ([] (const hb_tag_t &a, const hb_tag_t &b) { return a < b ? -1 : a > b ? 1 : 0; });++ hb_vector_t<char> specs;+ bool first = true;+ for (hb_tag_t tag : axis_tags)+ {+ Triple triple = axes_location.get (tag);+ if (!first)+ specs.push (',');+ first = false;++ hb_vector_t<char> tag_buf;+ _format_tag (tag, tag_buf);++ char buf[128];+ int len;+ if (triple.minimum == triple.middle && triple.middle == triple.maximum)+ {+ len = snprintf (buf, sizeof (buf), "%.*s=%g", (int) tag_buf.length, tag_buf.arrayZ, (double) triple.middle);+ }+ else if (std::isnan (triple.minimum) && std::isnan (triple.middle) && std::isnan (triple.maximum))+ {+ len = snprintf (buf, sizeof (buf), "%.*s=drop", (int) tag_buf.length, tag_buf.arrayZ);+ }+ else+ {+ len = snprintf (buf, sizeof (buf), "%.*s=%g:%g:%g", (int) tag_buf.length, tag_buf.arrayZ,+ (double) triple.minimum, (double) triple.middle, (double) triple.maximum);+ }+ if (unlikely (len < 0 || (size_t) len >= sizeof (buf))) return false;+ specs.extend (hb_bytes_t (buf, len));+ }+ if (specs.length)+ {+ hb_vector_t<char> opt;+ opt.extend (hb_bytes_t ("--variations=", 13));+ opt.extend (specs.as_array ());+ opt.push ('\0');+ if (opt.arrayZ) _append_arg (sb, opt.arrayZ);+ }+ return true;+}++/**+ * hb_subset_input_to_string_or_fail:+ * @input: a #hb_subset_input_t object.+ *+ * Produces a command line string representation of the given subset input+ * suitable for use with the `hb-subset` command line tool.+ *+ * Return value: (transfer full): A new #hb_blob_t containing the command line+ * string, or `NULL` if failed. Destroy with hb_blob_destroy().+ *+ * XSince: EXPERIMENTAL+ **/+hb_blob_t *+hb_subset_input_to_string_or_fail (hb_subset_input_t *input)+{+ if (unlikely (!input || input->in_error ()))+ return nullptr;++ hb_vector_t<char> sb;++ struct flag_option_t {+ hb_subset_flags_t flag;+ char option[32];+ };+ static const flag_option_t flag_options[] = {+ { HB_SUBSET_FLAGS_NO_HINTING, "no-hinting" },+ { HB_SUBSET_FLAGS_RETAIN_GIDS, "retain-gids" },+ { HB_SUBSET_FLAGS_DESUBROUTINIZE, "desubroutinize" },+ { HB_SUBSET_FLAGS_NAME_LEGACY, "name-legacy" },+ { HB_SUBSET_FLAGS_SET_OVERLAPS_FLAG, "set-overlaps-flag" },+ { HB_SUBSET_FLAGS_PASSTHROUGH_UNRECOGNIZED, "passthrough-tables" },+ { HB_SUBSET_FLAGS_NOTDEF_OUTLINE, "notdef-outline" },+ { HB_SUBSET_FLAGS_GLYPH_NAMES, "glyph-names" },+ { HB_SUBSET_FLAGS_NO_PRUNE_UNICODE_RANGES, "no-prune-unicode-ranges" },+ { HB_SUBSET_FLAGS_NO_LAYOUT_CLOSURE, "no-layout-closure" },+ { HB_SUBSET_FLAGS_OPTIMIZE_IUP_DELTAS, "optimize" },+ { HB_SUBSET_FLAGS_NO_BIDI_CLOSURE, "no-bidi-closure" },+#ifdef HB_EXPERIMENTAL_API+ { HB_SUBSET_FLAGS_IFTB_REQUIREMENTS, "iftb-requirements" },+ { HB_SUBSET_FLAGS_RETAIN_NUM_GLYPHS, "retain-num-glyphs" },+#endif+ { HB_SUBSET_FLAGS_DOWNGRADE_CFF2, "downgrade-cff2" },+ };++#ifdef HB_EXPERIMENTAL_API+ static_assert (sizeof (flag_options) / sizeof (flag_options[0]) == 15,+ "Check all flags in hb_subset_flags_t are handled here.");+#else+ static_assert (sizeof (flag_options) / sizeof (flag_options[0]) == 13,+ "Check all flags in hb_subset_flags_t are handled here.");+#endif++ for (const auto &fo : flag_options)+ {+ if (input->flags & fo.flag)+ {+ char buf[36];+ snprintf (buf, sizeof (buf), "--%s", fo.option);+ _append_arg (sb, buf);+ }+ }++ hb_subset_input_t *default_input = hb_subset_input_create_or_fail ();+ if (unlikely (!default_input))+ return nullptr;++ // Serialize all sets if they are not equal to their default setting:+#define PROCESS_NUMBER_SET(field, opt_name, ...) \+ if (!_is_set_default (input->sets.field, default_input->sets.field)) \+ _format_number_set_arg (input->sets.field, opt_name, sb, ##__VA_ARGS__)++#define PROCESS_TAG_SET(field, opt_name) \+ if (!_is_set_default (input->sets.field, default_input->sets.field)) \+ _format_tag_set_arg (input->sets.field, opt_name, sb)++ PROCESS_NUMBER_SET (unicodes, "unicodes", 16);+ PROCESS_NUMBER_SET (glyphs, "gids");+ PROCESS_NUMBER_SET (name_ids, "name-IDs");+ PROCESS_NUMBER_SET (name_languages, "name-languages");+ PROCESS_TAG_SET (layout_features, "layout-features");+ PROCESS_TAG_SET (layout_scripts, "layout-scripts");+ PROCESS_TAG_SET (drop_tables, "drop-tables");+ PROCESS_TAG_SET (no_subset_tables, "passthrough-tables");++#undef PROCESS_NUMBER_SET+#undef PROCESS_TAG_SET++ hb_subset_input_destroy (default_input);++ static_assert (sizeof (input->sets) / sizeof (hb_set_t*) == 8,+ "Check all sets in hb_subset_input_t::sets_t are handled here.");++ if (unlikely (!_format_glyph_map_arg (input->glyph_map, sb)))+ return nullptr;++ if (unlikely (!_format_axes_location_arg (input->axes_location, sb)))+ return nullptr;++ sb.push ('\0');+ if (unlikely (sb.in_error ()))+ return nullptr;++ unsigned len = 0;+ char *buf = sb.steal (&len);+ if (unlikely (!buf))+ return nullptr;++ return hb_blob_create_or_fail (buf, len, HB_MEMORY_MODE_WRITABLE, buf, hb_free);+}+#endif+/*** hb_subset_preprocess:* @source: a #hb_face_t object.diff --git a/thirdparty/harfbuzz/src/hb-subset-instancer-iup.cc b/thirdparty/harfbuzz/src/hb-subset-instancer-iup.ccindex f81ecfba826..1fb8349c3d1 100644--- a/thirdparty/harfbuzz/src/hb-subset-instancer-iup.cc+++ b/thirdparty/harfbuzz/src/hb-subset-instancer-iup.cc@@ -48,11 +48,11 @@ static void _iup_contour_bound_forced_set (const hb_array_t<const contour_point_unsigned next_i = 0;for (int i = len - 1; i >= 0; i--){- unsigned last_i = (len + i -1) % len;+ unsigned last_i = (len + i - 1) % len;for (unsigned j = 0; j < 2; j++){double cj, lcj, ncj;- int dj, ldj, ndj;+ double dj, ldj, ndj;if (j == 0){cj = static_cast<double> (contour_points.arrayZ[i].x);@@ -73,7 +73,7 @@ static void _iup_contour_bound_forced_set (const hb_array_t<const contour_point_}double c1, c2;- int d1, d2;+ double d1, d2;if (lcj <= ncj){c1 = lcj;@@ -92,7 +92,7 @@ static void _iup_contour_bound_forced_set (const hb_array_t<const contour_point_bool force = false;if (c1 == c2){- if (abs (d1 - d2) > tolerance && abs (dj) > tolerance)+ if (fabs (d1 - d2) > tolerance && fabs (dj) > tolerance)force = true;}else if (c1 <= cj && cj <= c2)@@ -107,15 +107,15 @@ static void _iup_contour_bound_forced_set (const hb_array_t<const contour_point_{if (cj < c1){- if (abs (dj) > tolerance &&- abs (dj - d1) > tolerance &&+ if (fabs (dj) > tolerance &&+ fabs (dj - d1) > tolerance &&((dj - tolerance < d1) != (d1 < d2)))force = true;}else{- if (abs (dj) > tolerance &&- abs (dj - d2) > tolerance &&+ if (fabs (dj) > tolerance &&+ fabs (dj - d2) > tolerance &&((d2 < dj + tolerance) != (d1 < d2)))force = true;}@@ -452,7 +452,8 @@ static bool _iup_contour_optimize (const hb_array_t<const contour_point_t> contohb_vector_t<bool> &rot_indices = scratch.rot_indices.reset ();const hb_array_t<const bool> opt_indices_array (opt_indices.arrayZ, opt_indices.length);- rotate_array (opt_indices_array, -k, rot_indices);+ if (unlikely (!rotate_array (opt_indices_array, -k, rot_indices)))+ return false;for (unsigned i = 0; i < n; i++)opt_indices.arrayZ[i] = rot_indices.arrayZ[i];@@ -534,13 +535,21 @@ bool iup_delta_optimize (const contour_point_vector_t& contour_points,if (unlikely (!end_points.alloc (count)))return false;- for (unsigned i = 0; i < count - 4; i++)- if (contour_points.arrayZ[i].is_end_point)+ if (count < 4)+ {+ for (unsigned i = 0; i < count; i++)end_points.push (i);+ }+ else+ {+ for (unsigned i = 0; i < count - 4; i++)+ if (contour_points.arrayZ[i].is_end_point)+ end_points.push (i);- /* phantom points */- for (unsigned i = count - 4; i < count; i++)- end_points.push (i);+ /* phantom points */+ for (unsigned i = count - 4; i < count; i++)+ end_points.push (i);+ }if (end_points.in_error ()) return false;diff --git a/thirdparty/harfbuzz/src/hb-subset-plan-member-list.hh b/thirdparty/harfbuzz/src/hb-subset-plan-member-list.hhindex 398fe81eca9..7ee9e4eddd3 100644--- a/thirdparty/harfbuzz/src/hb-subset-plan-member-list.hh+++ b/thirdparty/harfbuzz/src/hb-subset-plan-member-list.hh@@ -61,10 +61,16 @@ HB_SUBSET_PLAN_MEMBER (hb_set_t, drop_tables)// Old -> New glyph id mappingHB_SUBSET_PLAN_MEMBER (hb_map_t, glyph_map_gsub)+// Same mapping as glyph_map_gsub, as a flat array indexed by old gid,+// with HB_MAP_VALUE_INVALID entries for glyphs not retained. Sized to+// the highest retained GSUB gid plus one.+HB_SUBSET_PLAN_MEMBER (hb_vector_t<hb_codepoint_t>, glyph_map_gsub_flat)+HB_SUBSET_PLAN_MEMBER (hb_set_t, _glyphset)HB_SUBSET_PLAN_MEMBER (hb_set_t, _glyphset_gsub)HB_SUBSET_PLAN_MEMBER (hb_set_t, _glyphset_mathed)HB_SUBSET_PLAN_MEMBER (hb_set_t, _glyphset_colred)+HB_SUBSET_PLAN_MEMBER (hb_set_t, _glyphset_cmaped)//active lookups we'd like to retainHB_SUBSET_PLAN_MEMBER (hb_map_t, gsub_lookups)@@ -133,6 +139,20 @@ HB_SUBSET_PLAN_MEMBER (hb_hashmap_t E(<hb_tag_t, TripleDistances>), axes_triple_//retained old axis index -> new axis index mapping in fvar axis arrayHB_SUBSET_PLAN_MEMBER (hb_map_t, axes_index_map)+//old intermediate coords (post-fvar, post-avar-v1, pre-avar-v2) at new min/default/max+HB_SUBSET_PLAN_MEMBER (hb_hashmap_t E(<hb_tag_t, Triple>), old_intermediates)++//avar2: reachable old-space final-coord range per axis, as Triple+//(minimum, unused middle, maximum), F2Dot14-quantized. Only axes with a+//constraining range (narrower than [-1, +1]) have entries. Used to cull+//variation tuples/regions that a partial instance can never reach.+HB_SUBSET_PLAN_MEMBER (hb_hashmap_t E(<hb_tag_t, Triple>), avar2_reachable_ranges)++//avar2: self-contained pinned axes -> constant old-space final coord.+//These axes are removed from fvar/avar entirely; their contribution is+//baked into the variation tables like an ordinary pin at that coord.+HB_SUBSET_PLAN_MEMBER (hb_hashmap_t E(<hb_tag_t, double>), avar2_self_contained)+//axis_index->axis_tag mapping in fvar axis arrayHB_SUBSET_PLAN_MEMBER (hb_map_t, axes_old_index_tag_map)//vector of retained axis tags in the order of axes given in the 'fvar' tablediff --git a/thirdparty/harfbuzz/src/hb-subset-plan-var.cc b/thirdparty/harfbuzz/src/hb-subset-plan-var.ccindex fe29127d9a5..c341b931e93 100644--- a/thirdparty/harfbuzz/src/hb-subset-plan-var.cc+++ b/thirdparty/harfbuzz/src/hb-subset-plan-var.cc@@ -55,11 +55,308 @@}}+ /* Evaluate a variation-region tent at v, mirroring VarRegionAxis::evaluate+ * (invalid regions evaluate as constant 1). */+ static double+ _tent_eval (const Triple &tent, double v)+ {+ double start = tent.minimum, peak = tent.middle, end = tent.maximum;+ if (unlikely (start > peak || peak > end)) return 1.0;+ if (unlikely (start < 0.0 && end > 0.0 && peak != 0.0)) return 1.0;+ if (peak == 0.0 || v == peak) return 1.0;+ if (v <= start || end <= v) return 0.0;+ if (v < peak) return (v - start) / (peak - start);+ return (end - v) / (end - peak);+ }++ /* Range of a tent's scalar over an input interval [lo, hi]. The tent is+ * unimodal, so the extremes are at the interval endpoints, plus the peak+ * when it falls inside. */+ static void+ _tent_value_range (const Triple &tent, double lo, double hi,+ double *tmin, double *tmax)+ {+ double a = _tent_eval (tent, lo);+ double b = _tent_eval (tent, hi);+ *tmin = hb_min (a, b);+ *tmax = hb_max (a, b);+ if (lo <= tent.middle && tent.middle <= hi)+ *tmax = hb_max (*tmax, 1.0);+ }++ /* Compute conservative reachable old-space final-coord ranges per axis for+ * avar2 partial instancing. With offset compensation, the instanced font's+ * final coordinates equal the original font's over the retained user box,+ * so the reachable range of axis i's final coordinate is the range of+ * final_i = intermediate_i + delta_i(intermediates)+ * over the box of retained old-intermediate ranges: restricted axes span+ * their retained [a, b], free public axes [-1, +1], pinned axes sit at+ * their d_i, and hidden (private) axes at 0. Interval arithmetic over the+ * avar2 VarStore regions bounds delta_i. Mirrors fontTools'+ * _computeReachableRangesForAvar2, but computed from the original store at+ * plan time (the same quantity fontTools bounds via getExtremes on the+ * instanced store). Only constraining ranges (narrower than [-1, +1]) are+ * recorded. */+ static bool+ _compute_avar2_reachable_ranges (hb_subset_plan_t *plan,+ hb_array_t<const OT::AxisRecord> axes,+ const OT::avar *avar_table,+ bool detect_self_contained)+ {+ const OT::ItemVariationStore *var_store;+ const OT::DeltaSetIndexMap *varidx_map;+ if (!avar_table->get_v2_store_and_map (&var_store, &varidx_map))+ return false;++ /* Old-intermediate input box per axis. */+ hb_hashmap_t<hb_tag_t, hb_pair_t<double, double>> box;+ for (const auto &axis : axes)+ {+ hb_tag_t tag = axis.get_axis_tag ();+ double lo = -1.0, hi = +1.0;+ Triple *old_int;+ if (plan->user_axes_location.has (tag))+ {+ if (!plan->old_intermediates.has (tag, &old_int)) return false;+ lo = old_int->minimum;+ hi = old_int->maximum;+ }+ else if (axis.is_hidden ())+ lo = hi = 0.0; /* private axis: intermediate is always 0 */+ if (!box.set (tag, hb_pair (lo, hi))) return false;+ }++ hb_vector_t<hb_hashmap_t<hb_tag_t, Triple>> regions;+ if (!var_store->get_region_list ().get_var_regions (plan->axes_old_index_tag_map, regions))+ return false;++ hb_hashmap_t<hb_tag_t, unsigned> grid_pos;+ hb_vector_t<hb_vector_t<double>> grid_points;+ for (unsigned i = 0; i < axes.length; i++)+ {+ grid_pos.reset ();+ grid_points.reset ();++ hb_tag_t tag = axes[i].get_axis_tag ();+ hb_pair_t<double, double> *identity;+ if (!box.has (tag, &identity)) return false;++ /* Collect the row's active regions (non-zero delta). A varidx (or the+ * implicit identity mapping) that doesn't resolve to a real store row+ * behaves as "no variation" at runtime, so it contributes no regions;+ * this also covers a NULL VarStore. */+ hb_vector_t<hb_pair_t<int, unsigned>> active; /* (delta, region index) */+ uint32_t varidx = varidx_map->map (i);+ /* Runtime treats out-of-range delta-set indices as zero. */+ if (varidx != HB_OT_LAYOUT_NO_VARIATIONS_INDEX &&+ !var_store->has_delta_set (varidx))+ varidx = HB_OT_LAYOUT_NO_VARIATIONS_INDEX;+ if (varidx != HB_OT_LAYOUT_NO_VARIATIONS_INDEX)+ {+ unsigned outer = varidx >> 16;+ unsigned inner = varidx & 0xFFFF;+ const OT::VarData &vd = var_store->get_sub_table (outer);+ const OT::HBUINT8 *delta_bytes = vd.get_delta_bytes ();+ unsigned row_size = vd.get_row_size ();+ unsigned region_count = vd.get_region_index_count ();+ for (unsigned r = 0; r < region_count; r++)+ {+ int delta = vd.get_item_delta_fast (inner, r, delta_bytes, row_size);+ if (!delta) continue;+ unsigned region_idx = vd.get_region_index (r);+ if (region_idx >= regions.length) return false;+ active.push (hb_pair (delta, region_idx));+ }+ if (active.in_error ()) return false;+ }++ /* The delta is piecewise multilinear in the axis coordinates (each+ * region scalar is a product of independent per-axis tents), so over+ * the box its exact extremes are attained at vertices of the grid of+ * per-axis tent breakpoints. Enumerate that grid when it is small+ * (real fonts); otherwise fall back to per-region interval+ * arithmetic, which ignores correlations between regions and is+ * looser but still conservative. Mirrors fontTools'+ * VarStore.getExtremes. */+ constexpr unsigned MAX_GRID = 1u << 14;+ bool exact = true;+ double dmin = 0.0, dmax = 0.0; /* delta extremes, F2Dot14 units */+ double vmin = 0.0, vmax = 0.0; /* identity + delta extremes, coord units */++ /* Grid axes: the target axis (identity term), plus every axis a valid+ * tent of an active region references. */+ auto add_grid_axis = [&] (hb_tag_t t) -> int+ {+ unsigned *pos;+ if (grid_pos.has (t, &pos)) return (int) *pos;+ unsigned new_pos = grid_pos.get_population ();+ hb_pair_t<double, double> *input;+ double blo = -1.0, bhi = +1.0;+ if (box.has (t, &input)) { blo = input->first; bhi = input->second; }+ grid_points.push (hb_vector_t<double> ());+ if (grid_points.in_error ()) return -1;+ auto &points = grid_points[new_pos];+ points.push (blo);+ points.push (bhi);+ if (points.in_error () || !grid_pos.set (t, new_pos)) return -1;+ return (int) new_pos;+ };++ if (add_grid_axis (tag) < 0) return false;+ /* Per active region: (grid axis position, tent) for its valid tents. */+ hb_vector_t<hb_vector_t<hb_pair_t<unsigned, Triple>>> region_tents;+ for (const auto &ar : active)+ {+ region_tents.push (hb_vector_t<hb_pair_t<unsigned, Triple>> ());+ if (region_tents.in_error ()) return false;+ auto &tents = region_tents[region_tents.length - 1];+ for (const auto &_ : regions[ar.second])+ {+ const Triple &tent = _.second;+ /* Tents the runtime ignores (constant scalar 1) add no breakpoints. */+ if (tent.middle == 0.0 ||+ tent.minimum > tent.middle || tent.middle > tent.maximum ||+ (tent.minimum < 0.0 && tent.maximum > 0.0))+ continue;+ int pos = add_grid_axis (_.first);+ if (pos < 0) return false;+ auto &points = grid_points[pos];+ double blo = points[0], bhi = points[1];+ points.push (hb_clamp (tent.minimum, blo, bhi));+ points.push (hb_clamp (tent.middle, blo, bhi));+ points.push (hb_clamp (tent.maximum, blo, bhi));+ tents.push (hb_pair ((unsigned) pos, tent));+ if (points.in_error () || tents.in_error ()) return false;+ }+ }++ unsigned grid_size = 1;+ for (auto &points : grid_points)+ {+ points.qsort ([] (const double &a, const double &b) -> int+ { return a < b ? -1 : a > b ? +1 : 0; });+ unsigned n = 0;+ for (unsigned j = 0; j < points.length; j++)+ if (!n || points.arrayZ[j] != points.arrayZ[n - 1])+ points.arrayZ[n++] = points.arrayZ[j];+ points.shrink (n);+ if (grid_size > MAX_GRID / points.length) { exact = false; break; }+ grid_size *= points.length;+ }++ if (exact)+ {+ unsigned target_pos = 0; /* the target axis was added first */+ hb_vector_t<unsigned> odometer;+ if (!odometer.resize (grid_pos.get_population ())) return false;+ bool first = true;+ while (true)+ {+ double delta_sum = 0.0;+ for (unsigned r = 0; r < active.length; r++)+ {+ double scalar = 1.0;+ for (const auto &pt : region_tents[r])+ {+ double v = grid_points[pt.first][odometer[pt.first]];+ scalar *= _tent_eval (pt.second, v);+ if (scalar == 0.0) break;+ }+ delta_sum += scalar * active[r].first;+ }+ double coord = grid_points[target_pos][odometer[target_pos]];+ double value = coord + delta_sum / 16384.0;+ if (first)+ {+ dmin = dmax = delta_sum;+ vmin = vmax = value;+ first = false;+ }+ else+ {+ dmin = hb_min (dmin, delta_sum); dmax = hb_max (dmax, delta_sum);+ vmin = hb_min (vmin, value); vmax = hb_max (vmax, value);+ }+ unsigned k = 0;+ for (; k < odometer.length; k++)+ {+ if (++odometer[k] < grid_points[k].length) break;+ odometer[k] = 0;+ }+ if (k == odometer.length) break;+ }+ }+ else+ {+ for (const auto &ar : active)+ {+ int delta = ar.first;+ double smin = 1.0, smax = 1.0;+ for (const auto &_ : regions[ar.second])+ {+ hb_pair_t<double, double> *input;+ double blo = -1.0, bhi = +1.0;+ if (box.has (_.first, &input)) { blo = input->first; bhi = input->second; }+ double tmin, tmax;+ _tent_value_range (_.second, blo, bhi, &tmin, &tmax);+ smin *= tmin;+ smax *= tmax;+ if (smax == 0.0) break;+ }+ if (delta > 0) { dmin += smin * delta; dmax += smax * delta; }+ else { dmin += smax * delta; dmax += smin * delta; }+ }+ vmin = identity->first + dmin / 16384.0;+ vmax = identity->second + dmax / 16384.0;+ }+ /* A pinned axis whose delta is constant over the box is self-contained:+ * its final coordinate is a constant. It can be removed from fvar/avar+ * and its contribution baked into the variation tables like an ordinary+ * pin at that coordinate (in old final space). Round the delta alone+ * and add it to the exact quantized intermediate, matching the runtime+ * (map_coords_2_14) and fontTools. */+ Triple *user;+ if (detect_self_contained && dmin == dmax &&+ plan->user_axes_location.has (tag, &user) && user->is_point ())+ {+ int v_int = (int) roundf ((float) identity->first * 16384.f) ++ (int) roundf ((float) dmin);+ v_int = hb_clamp (v_int, -(1 << 14), +(1 << 14));+ if (!plan->avar2_self_contained.set (tag, v_int / 16384.0)) return false;+ continue; /* axis is dropped; no region can reference it afterwards */+ }++ /* Pad by one F2Dot14 unit against rounding differences with the+ * runtime's fixed-point evaluation. */+ double lo = hb_clamp (vmin - 1.0 / 16384.0, -1.0, +1.0);+ double hi = hb_clamp (vmax + 1.0 / 16384.0, -1.0, +1.0);+ lo = floor (lo * 16384.0) / 16384.0;+ hi = ceil (hi * 16384.0) / 16384.0;+ if (lo <= -1.0 && hi >= +1.0)+ continue; /* not constraining */+ if (!plan->avar2_reachable_ranges.set (tag, Triple (lo, hb_clamp (0.0, lo, hi), hi)))+ return false;+ }+ return true;+ }++#ifndef HB_NO_OT_FONT_CFFstatic inline hb_font_t*_get_hb_font_with_variations (const hb_subset_plan_t *plan){hb_font_t *font = hb_font_create (plan->source);+ if (plan->has_avar2)+ {+ /* Under avar2, instancing applies only to the self-contained pins,+ * whose constant final coordinates the plan holds in normalized_coords.+ * Setting user-space variations would run the full avar2 mapping and+ * bake contributions that remain live in the instance's variations. */+ hb_font_set_var_coords_normalized (font, plan->normalized_coords.arrayZ,+ plan->normalized_coords.length);+ return font;+ }+hb_vector_t<hb_variation_t> vars;if (!vars.alloc (plan->user_axes_location.get_population ())) {hb_font_destroy (font);@@ -77,6 +374,7 @@hb_font_set_variations (font, vars.arrayZ, plan->user_axes_location.get_population ());return font;}+#endiftemplate<typename ItemVarStore>void@@ -251,40 +549,128 @@ normalize_axes_location (hb_face_t *face, hb_subset_plan_t *plan)if (has_avar){const OT::avar* avar_table = face->table.avar;+ unsigned coords_len = last_idx + 1;+if (avar_table->has_v2_data () && !plan->all_axes_pinned){- DEBUG_MSG (SUBSET, nullptr, "Partial-instancing avar2 table is not supported.");- return false;- }+ /* avar2 partial instancing: use v1-only mapping to get intermediate-space+ * coords. These are used for IVS rebasing and offset compensation. */+ plan->has_avar2 = true;- unsigned coords_len = last_idx + 1;- if (!plan->check_success (avar_table->map_coords_2_14 (normalized_mins.arrayZ, coords_len)) ||- !plan->check_success (avar_table->map_coords_2_14 (normalized_defaults.arrayZ, coords_len)) ||- !plan->check_success (avar_table->map_coords_2_14 (normalized_maxs.arrayZ, coords_len)))- return false;+ if (!plan->check_success (avar_table->map_coords_2_14 (normalized_mins.arrayZ, coords_len, true)) ||+ !plan->check_success (avar_table->map_coords_2_14 (normalized_defaults.arrayZ, coords_len, true)) ||+ !plan->check_success (avar_table->map_coords_2_14 (normalized_maxs.arrayZ, coords_len, true)))+ return false;- for (const auto& _ : + hb_enumerate (axes))- {- unsigned i = _.first;- hb_tag_t axis_tag = _.second.get_axis_tag ();- if (plan->user_axes_location.has (axis_tag))+ for (const auto& _ : + hb_enumerate (axes)){- plan->axes_location.set (axis_tag, Triple ((double) normalized_mins[i],- (double) normalized_defaults[i],- (double) normalized_maxs[i]));- float normalized_default = normalized_defaults[i];- if (normalized_default == -0.f)- normalized_default = 0.f; // Normalize -0 to 0- if (normalized_default != 0.f)- plan->pinned_at_default = false;+ unsigned i = _.first;+ hb_tag_t axis_tag = _.second.get_axis_tag ();+ if (plan->user_axes_location.has (axis_tag))+ {+ /* Store intermediate-space coords for offset compensation,+ * segment-map renormalization, and IVS rebasing. */+ plan->old_intermediates.set (axis_tag, Triple ((double) normalized_mins[i],+ (double) normalized_defaults[i],+ (double) normalized_maxs[i]));+ }+ }- plan->normalized_coords[i] = roundf (normalized_default * 16384.f);+ /* Reachable-range computation also detects self-contained pinned+ * axes: pinned axes whose final coordinate is constant. Those are+ * removed from fvar, so suppress the detection when the face has+ * tables that cannot follow: CFF2 has no partial-pin instancing path+ * (its 'pinned' path flattens ALL blends; lift this once+ * https://github.com/harfbuzz/harfbuzz/pull/4710 lands, porting+ * fontTools' instantiateCFF2 from+ * https://github.com/fonttools/fonttools/pull/3506), and VARC passes+ * through verbatim with explicit fvar axis indices that renumbering+ * would desynchronize. Such axes stay in fvar as ordinary hidden+ * pins. */+ bool detect_self_contained = true;+ for (hb_tag_t table_tag : { HB_TAG ('C','F','F','2'), HB_TAG ('V','A','R','C') })+ {+ hb_blob_t *blob = hb_face_reference_table (face, table_tag);+ if (hb_blob_get_length (blob))+ detect_self_contained = false;+ hb_blob_destroy (blob);+ }+ if (!_compute_avar2_reachable_ranges (plan, axes, avar_table,+ detect_self_contained))+ return false;++ /* Keep all axes in fvar (pinned ones as hidden), EXCEPT self-contained+ * pinned axes, which are removed entirely. */+ plan->axes_index_map.reset ();+ plan->axis_tags.reset ();+ unsigned retained_axis_idx = 0;+ for (const auto& _ : + hb_enumerate (axes))+ {+ unsigned i = _.first;+ hb_tag_t axis_tag = _.second.get_axis_tag ();+ if (plan->avar2_self_contained.has (axis_tag))+ continue;+ plan->axes_index_map.set (i, retained_axis_idx++);+ plan->axis_tags.push (axis_tag);+ }+ /* The other tables see ONLY the self-contained pins, as an ordinary+ * partial instancing in old final-coordinate space; the standard+ * instancing machinery bakes those axes' contributions in. The+ * remaining restriction is carried entirely by avar. */+ plan->axes_location.reset ();+ if (plan->avar2_self_contained.get_population ())+ {+ bool sc_pinned_at_default = true;+ for (auto _ : plan->avar2_self_contained)+ {+ plan->axes_location.set (_.first, Triple (_.second, _.second, _.second));+ if (_.second != 0.0)+ sc_pinned_at_default = false;+ }+ for (const auto& _ : + hb_enumerate (axes))+ {+ double *v;+ plan->normalized_coords[_.first] =+ plan->avar2_self_contained.has (_.second.get_axis_tag (), &v)+ ? (int) roundf ((float) (*v * 16384.0)) : 0;+ }+ plan->pinned_at_default = sc_pinned_at_default;+ }+ else+ plan->normalized_coords.shrink (0);+ }+ else+ {+ /* Standard avar v1 (or v1+v2 with all axes pinned) */+ if (!plan->check_success (avar_table->map_coords_2_14 (normalized_mins.arrayZ, coords_len)) ||+ !plan->check_success (avar_table->map_coords_2_14 (normalized_defaults.arrayZ, coords_len)) ||+ !plan->check_success (avar_table->map_coords_2_14 (normalized_maxs.arrayZ, coords_len)))+ return false;++ for (const auto& _ : + hb_enumerate (axes))+ {+ unsigned i = _.first;+ hb_tag_t axis_tag = _.second.get_axis_tag ();+ if (plan->user_axes_location.has (axis_tag))+ {+ plan->axes_location.set (axis_tag, Triple ((double) normalized_mins[i],+ (double) normalized_defaults[i],+ (double) normalized_maxs[i]));+ float normalized_default = normalized_defaults[i];+ if (normalized_default == -0.f)+ normalized_default = 0.f;+ if (normalized_default != 0.f)+ plan->pinned_at_default = false;++ plan->normalized_coords[i] = roundf (normalized_default * 16384.f);+ }}}}return true;}+#ifndef HB_NO_OT_FONT_CFFvoidupdate_instance_metrics_map_from_cff2 (hb_subset_plan_t *plan){@@ -323,17 +709,23 @@ update_instance_metrics_map_from_cff2 (hb_subset_plan_t *plan)if (has_bounds_info){plan->head_maxp_info.xMin = hb_min (plan->head_maxp_info.xMin, extents.x_bearing);- plan->head_maxp_info.xMax = hb_max (plan->head_maxp_info.xMax, extents.x_bearing + extents.width);+ plan->head_maxp_info.xMax = hb_max (plan->head_maxp_info.xMax,+ hb_saturate_add (extents.x_bearing, extents.width));plan->head_maxp_info.yMax = hb_max (plan->head_maxp_info.yMax, extents.y_bearing);- plan->head_maxp_info.yMin = hb_min (plan->head_maxp_info.yMin, extents.y_bearing + extents.height);+ plan->head_maxp_info.yMin = hb_min (plan->head_maxp_info.yMin,+ hb_saturate_add (extents.y_bearing, extents.height));}if (_hmtx.has_data ()){- int hori_aw = _hmtx.get_advance_without_var_unscaled (old_gid);+ double hori_aw = _hmtx.get_advance_without_var_unscaled (old_gid);if (_hmtx.var_table.get_length ())- hori_aw += (int) roundf (_hmtx.var_table->get_advance_delta_unscaled (old_gid, font->coords, font->num_coords,- hvar_store_cache));+ hori_aw += (double) roundf (_hmtx.var_table->get_advance_delta_unscaled (old_gid, font->coords, font->num_coords,+ hvar_store_cache));+ /* Malicious deltas can take the advance out of the UFWORD range that+ * hmtx serialization stores. Clamp, to keep downstream consumers+ * (e.g. CFF width optimizer) bounded and consistent with hmtx. */+ hori_aw = hb_clamp (hori_aw, 0., 65535.);int lsb = extents.x_bearing;if (!has_bounds_info){@@ -345,17 +737,18 @@ update_instance_metrics_map_from_cff2 (hb_subset_plan_t *plan)if (_vmtx.has_data ()){- int vert_aw = _vmtx.get_advance_without_var_unscaled (old_gid);+ double vert_aw = _vmtx.get_advance_without_var_unscaled (old_gid);if (_vmtx.var_table.get_length ())- vert_aw += (int) roundf (_vmtx.var_table->get_advance_delta_unscaled (old_gid, font->coords, font->num_coords,- vvar_store_cache));+ vert_aw += (double) roundf (_vmtx.var_table->get_advance_delta_unscaled (old_gid, font->coords, font->num_coords,+ vvar_store_cache));+ vert_aw = hb_clamp (vert_aw, 0., 65535.);hb_position_t vorg_x = 0;hb_position_t vorg_y = 0;int tsb = 0;if (has_bounds_info &&hb_font_get_glyph_v_origin (font, old_gid, &vorg_x, &vorg_y)){- tsb = vorg_y - extents.y_bearing;+ tsb = hb_saturate_sub (vorg_y, extents.y_bearing);} else {_vmtx.get_leading_bearing_without_var_unscaled (old_gid, &tsb);}@@ -370,6 +763,7 @@ update_instance_metrics_map_from_cff2 (hb_subset_plan_t *plan)if (vvar_store_cache)_vmtx.var_table->get_var_store ().destroy_cache (vvar_store_cache);}+#endifboolget_instance_glyphs_contour_points (hb_subset_plan_t *plan)diff --git a/thirdparty/harfbuzz/src/hb-subset-plan.cc b/thirdparty/harfbuzz/src/hb-subset-plan.ccindex 767c1bf2dc4..5408dfc77a0 100644--- a/thirdparty/harfbuzz/src/hb-subset-plan.cc+++ b/thirdparty/harfbuzz/src/hb-subset-plan.cc@@ -451,6 +451,14 @@ _populate_gids_to_retain (hb_subset_plan_t* plan,plan->_glyphset_gsub.add (0); // Not-def_cmap_closure (plan->source, &plan->unicodes, &plan->_glyphset_gsub);+ plan->_glyphset_cmaped = plan->_glyphset_gsub;++ if (!drop_tables->has (HB_OT_TAG_MATH))+ {+ _math_closure (plan, &plan->_glyphset_gsub);+ _remove_invalid_gids (&plan->_glyphset_gsub, plan->source->get_num_glyphs ());+ }+ plan->_glyphset_mathed = plan->_glyphset_gsub;#ifndef HB_NO_SUBSET_LAYOUTlayout_populate_gids_to_retain(plan, drop_tables);@@ -458,14 +466,7 @@ _populate_gids_to_retain (hb_subset_plan_t* plan,_remove_invalid_gids (&plan->_glyphset_gsub, plan->source->get_num_glyphs ());- plan->_glyphset_mathed = plan->_glyphset_gsub;- if (!drop_tables->has (HB_OT_TAG_MATH))- {- _math_closure (plan, &plan->_glyphset_mathed);- _remove_invalid_gids (&plan->_glyphset_mathed, plan->source->get_num_glyphs ());- }-- hb_set_t cur_glyphset = plan->_glyphset_mathed;+ hb_set_t cur_glyphset = plan->_glyphset_gsub;if (!drop_tables->has (HB_OT_TAG_COLR)){_colr_closure (plan, &cur_glyphset);@@ -507,18 +508,27 @@ _populate_gids_to_retain (hb_subset_plan_t* plan,#endif}-static void+static bool_create_glyph_map_gsub (const hb_set_t* glyph_set_gsub,const hb_map_t* glyph_map,- hb_map_t* out)+ hb_map_t* out,+ hb_vector_t<hb_codepoint_t>* out_flat){+ hb_codepoint_t max_gid = HB_SET_VALUE_INVALID;+ hb_set_previous (glyph_set_gsub, &max_gid);+ unsigned flat_size = max_gid == HB_SET_VALUE_INVALID ? 0 : max_gid + 1;+ if (unlikely (!out_flat->resize_dirty (flat_size)))+ return false;+ hb_memset (out_flat->arrayZ, 0xFF, flat_size * sizeof (hb_codepoint_t));+out->alloc (glyph_set_gsub->get_population ());- + hb_iter (glyph_set_gsub)- | hb_map ([&] (hb_codepoint_t gid) {- return hb_codepoint_pair_t (gid, glyph_map->get (gid));- })- | hb_sink (out)- ;+ for (auto gid : *glyph_set_gsub)+ {+ hb_codepoint_t new_gid = glyph_map->get (gid);+ out->set (gid, new_gid);+ out_flat->arrayZ[gid] = new_gid;+ }+ return !out->in_error ();}static bool@@ -647,6 +657,7 @@ hb_subset_plan_t::hb_subset_plan_t (hb_face_t *face,all_axes_pinned = false;pinned_at_default = true;has_gdef_varstore = false;+ has_avar2 = false;#ifdef HB_EXPERIMENTAL_APIfor (auto _ : input->name_table_overrides)@@ -708,10 +719,12 @@ hb_subset_plan_t::hb_subset_plan_t (hb_face_t *face,}#endif- _create_glyph_map_gsub (+ if (!check_success (_create_glyph_map_gsub (&_glyphset_gsub,glyph_map,- &glyph_map_gsub);+ &glyph_map_gsub,+ &glyph_map_gsub_flat)))+ return;// Now that we have old to new gid map update the unicode to new gid list.for (unsigned i = 0; i < unicode_to_new_gid_list.length; i++)@@ -743,8 +756,10 @@ hb_subset_plan_t::hb_subset_plan_t (hb_face_t *face,if (unlikely (in_error ()))return;-#ifndef HB_NO_VAR+#if !defined(HB_NO_VAR) && !defined(HB_NO_OT_FONT_CFF)update_instance_metrics_map_from_cff2 (this);+#endif+#ifndef HB_NO_VARif (!check_success (get_instance_glyphs_contour_points (this)))return;#endifdiff --git a/thirdparty/harfbuzz/src/hb-subset-plan.hh b/thirdparty/harfbuzz/src/hb-subset-plan.hhindex 2a935b8f134..a84a305fe79 100644--- a/thirdparty/harfbuzz/src/hb-subset-plan.hh+++ b/thirdparty/harfbuzz/src/hb-subset-plan.hh@@ -169,6 +169,9 @@ struct hb_subset_plan_t// whether GDEF ItemVariationStore is retainedmutable bool has_gdef_varstore;+ // whether we're doing avar2 partial instancing+ bool has_avar2;+#define HB_SUBSET_PLAN_MEMBER(Type, Name) Type Name;#include "hb-subset-plan-member-list.hh"#undef HB_SUBSET_PLAN_MEMBER@@ -238,6 +241,18 @@ struct hb_subset_plan_treturn &_glyphset_gsub;}+ /*+ * Old-to-new glyph id mapping for GSUB glyphs, through the flat+ * array; returns HB_MAP_VALUE_INVALID for glyphs not retained.+ */+ inline hb_codepoint_t+ map_gsub_glyph (hb_codepoint_t old_gid) const+ {+ return old_gid < glyph_map_gsub_flat.length+ ? glyph_map_gsub_flat.arrayZ[old_gid]+ : HB_MAP_VALUE_INVALID;+ }+/** The total number of output glyphs in the final subset.*/diff --git a/thirdparty/harfbuzz/src/hb-subset-serialize.h b/thirdparty/harfbuzz/src/hb-subset-serialize.hindex 9035d4ced7a..a3ca3bfbae6 100644--- a/thirdparty/harfbuzz/src/hb-subset-serialize.h+++ b/thirdparty/harfbuzz/src/hb-subset-serialize.h@@ -26,6 +26,11 @@#ifndef HB_SUBSET_SERIALIZE_H#define HB_SUBSET_SERIALIZE_H+#if !defined(HB_SUBSET_H_IN) && !defined(HB_NO_SINGLE_HEADER_ERROR)+// Disabled to not break pre-existing users.+//#error "Include <hb-subset.h> instead."+#endif+#include "hb.h"HB_BEGIN_DECLSdiff --git a/thirdparty/harfbuzz/src/hb-subset-table-var.cc b/thirdparty/harfbuzz/src/hb-subset-table-var.ccindex b569b08a008..2aa2ad565fe 100644--- a/thirdparty/harfbuzz/src/hb-subset-table-var.cc+++ b/thirdparty/harfbuzz/src/hb-subset-table-var.cc@@ -28,13 +28,19 @@ bool _hb_subset_table_var (hb_subset_plan_t *plan, hb_vector_t<char> &buf, hb_t*success = _hb_subset_table<const OT::avar> (plan, buf);return true;case HB_TAG('c','v','a','r'):- if (plan->user_axes_location.is_empty ())+ /* TODO: For avar2 partial instancing, cull unreachable tuple+ * variations (avar2_reachable_ranges) instead of passing through. */+ if (plan->user_axes_location.is_empty () ||+ (plan->has_avar2 && !plan->normalized_coords))*success = _hb_subset_table_passthrough (plan, tag);else*success = _hb_subset_table<const OT::cvar> (plan, buf);return true;case HB_TAG('M','V','A','R'):- if (plan->user_axes_location.is_empty ())+ /* TODO: For avar2 partial instancing, cull unreachable VarStore+ * regions (avar2_reachable_ranges) instead of passing through. */+ if (plan->user_axes_location.is_empty () ||+ (plan->has_avar2 && !plan->normalized_coords))*success = _hb_subset_table_passthrough (plan, tag);else*success = _hb_subset_table<const OT::MVAR> (plan, buf);diff --git a/thirdparty/harfbuzz/src/hb-subset.cc b/thirdparty/harfbuzz/src/hb-subset.ccindex d1ca60e63e5..d3f97f4bbc6 100644--- a/thirdparty/harfbuzz/src/hb-subset.cc+++ b/thirdparty/harfbuzz/src/hb-subset.cc@@ -247,6 +247,15 @@ _dependencies_satisfied (hb_subset_plan_t *plan, hb_tag_t tag,return !plan->normalized_coords || !pending_subset_tags.has (HB_TAG('g','l','y','f'));case HB_TAG('G','P','O','S'):return plan->all_axes_pinned || !pending_subset_tags.has (HB_TAG('G','D','E','F'));+ /* For avar2, variation tables must wait for avar to be subsetted first. */+ case HB_TAG('g','v','a','r'):+ case HB_TAG('c','v','a','r'):+ case HB_TAG('H','V','A','R'):+ case HB_TAG('V','V','A','R'):+ case HB_TAG('M','V','A','R'):+ case HB_TAG('G','D','E','F'):+ case HB_TAG('C','F','F','2'):+ return !plan->has_avar2 || !pending_subset_tags.has (HB_TAG('a','v','a','r'));default:return true;}diff --git a/thirdparty/harfbuzz/src/hb-subset.h b/thirdparty/harfbuzz/src/hb-subset.hindex 49cd12763d4..e3308506d7c 100644--- a/thirdparty/harfbuzz/src/hb-subset.h+++ b/thirdparty/harfbuzz/src/hb-subset.h@@ -26,9 +26,15 @@#ifndef HB_SUBSET_H#define HB_SUBSET_H+#define HB_SUBSET_H_IN#include "hb.h"#include "hb-ot.h"+#include "hb-subset-serialize.h"+#include "hb-subset-depend.h"+#include "hb-subset-serialize.h"++#undef HB_SUBSET_H_INHB_BEGIN_DECLS@@ -84,9 +90,12 @@ typedef struct hb_subset_plan_t hb_subset_plan_t;* HB_SUBSET_FLAGS_RETAIN_GIDS then the number of glyphs in the font won't* be reduced as a result of subsetting. If necessary empty glyphs will be* included at the end of the font to keep the number of glyphs unchanged.- * @HB_SUBSET_FLAGS_DOWNGRADE_CFF2: If set and instantiating a variable font,- * convert the output CFF2 table to CFF1. This enables compatibility with older- * renderers that don't support CFF2. Since: 13.0.0+ * @HB_SUBSET_FLAGS_DOWNGRADE_CFF2: If set and instantiating a variable font+ * with all axes pinned, convert the output CFF2 table to CFF1. This enables+ * compatibility with older renderers that don't support CFF2. Since: 13.0.0+ * @HB_SUBSET_FLAGS_CFF_IDENTITY_CHARSET: If set and subsetting a CID-keyed CFF+ * font, the output CFF charset will use sequential identity CIDs (CID = new+ * GID) rather than preserving the original CIDs. Since: 14.3.0** List of boolean properties that can be configured on the subset input.*@@ -111,6 +120,7 @@ typedef enum { /*< flags >*/HB_SUBSET_FLAGS_RETAIN_NUM_GLYPHS = 0x00002000u,#endifHB_SUBSET_FLAGS_DOWNGRADE_CFF2 = 0x00004000u,+ HB_SUBSET_FLAGS_CFF_IDENTITY_CHARSET = 0x00008000u,} hb_subset_flags_t;/**@@ -228,6 +238,9 @@ hb_subset_axis_range_to_string (hb_subset_input_t *input,unsigned size);#ifdef HB_EXPERIMENTAL_API+HB_EXTERN hb_blob_t *+hb_subset_input_to_string_or_fail (hb_subset_input_t *input);+HB_EXTERN hb_bool_thb_subset_input_override_name_table (hb_subset_input_t *input,hb_ot_name_id_t name_id,diff --git a/thirdparty/harfbuzz/src/hb-uniscribe.cc b/thirdparty/harfbuzz/src/hb-uniscribe.ccindex cbef4949796..46146362a23 100644--- a/thirdparty/harfbuzz/src/hb-uniscribe.cc+++ b/thirdparty/harfbuzz/src/hb-uniscribe.cc@@ -864,9 +864,10 @@ retry:hb_glyph_position_t *pos = &buffer->pos[i];/* TODO vertical */- pos->x_advance = x_mult * (int32_t) info->mask;- pos->x_offset = x_mult * (backward ? -info->var1.i32 : info->var1.i32);- pos->y_offset = y_mult * info->var2.i32;+ pos->x_advance = hb_clamp_to<hb_position_t> (x_mult * (int32_t) info->mask);+ double x_offset = backward ? -(double) info->var1.i32 : info->var1.i32;+ pos->x_offset = hb_clamp_to<hb_position_t> (x_mult * x_offset);+ pos->y_offset = hb_clamp_to<hb_position_t> (y_mult * info->var2.i32);}if (backward)diff --git a/thirdparty/harfbuzz/src/hb-vector-buf.hh b/thirdparty/harfbuzz/src/hb-vector-buf.hhindex d09f907de6a..5624cd181ed 100644--- a/thirdparty/harfbuzz/src/hb-vector-buf.hh+++ b/thirdparty/harfbuzz/src/hb-vector-buf.hh@@ -36,6 +36,9 @@HB_INTERNAL const char *hb_vector_decimal_point_get (void);+static const double _hb_vector_buf_pow10[13] = {1., 1e1, 1e2, 1e3, 1e4, 1e5, 1e6,+ 1e7, 1e8, 1e9, 1e10, 1e11, 1e12};+struct hb_vector_buf_t : hb_vector_t<char>{unsigned precision = 2;@@ -46,7 +49,9 @@ struct hb_vector_buf_t : hb_vector_t<char>bool append_len (const char *s, unsigned l){unsigned old_len = length;- if (unlikely (!resize_dirty ((int) (old_len + l))))+ unsigned new_len;+ if (unlikely (hb_unsigned_add_overflows (old_len, l, &new_len) ||+ !resize_dirty ((int) new_len)))return false;hb_memcpy (arrayZ + old_len, s, l);return true;@@ -91,6 +96,48 @@ struct hb_vector_buf_t : hb_vector_t<char>return;}+ /* Fast path: fixed-point decimal via integer math. @v has a+ * 24-bit significand and 5^12 has 28 bits, so v*10^p is exact in+ * a double for p <= 12; rounding it half-to-even therefore+ * matches snprintf "%.pf" output digit-for-digit, while skipping+ * the (much slower) printf floating-point formatting and any+ * locale decimal-point fix-up. */+ double scaled = (double) v * _hb_vector_buf_pow10[p];+ if (likely (fabs (scaled) < 9.0e18))+ {+ double fl = floor (scaled);+ double diff = scaled - fl;+ int64_t n = (int64_t) fl;+ if (diff > 0.5 || (diff == 0.5 && (n & 1)))+ n++;++ uint64_t u = (uint64_t) (n < 0 ? -n : n);+ unsigned frac = p;+ while (frac && !(u % 10))+ {+ u /= 10;+ frac--;+ }++ char tmp[24];+ char *end = tmp + sizeof (tmp);+ char *s = end;+ unsigned d = 0;+ do+ {+ *--s = (char) ('0' + (char) (u % 10));+ u /= 10;+ if (++d == frac)+ *--s = '.';+ }+ while (u || d < frac + 1);+ if (v < 0.f)+ *--s = '-';++ append_len (s, (unsigned) (end - s));+ return;+ }+char fmt[6];snprintf (fmt, sizeof (fmt), "%%.%uf", p);char out[128];@@ -153,9 +200,14 @@ struct hb_vector_buf_t : hb_vector_t<char>bool append_base64 (const uint8_t *data, unsigned len){- unsigned out_len = ((len + 2) / 3) * 4;+ /* Output is 4 bytes per 3 input bytes; compute without overflowing. */+ unsigned ngroups = len / 3 + (len % 3 != 0);+ unsigned out_len;unsigned old_len = length;- if (unlikely (!resize_dirty ((int) (old_len + out_len))))+ unsigned new_len;+ if (unlikely (hb_unsigned_mul_overflows (ngroups, 4, &out_len) ||+ hb_unsigned_add_overflows (old_len, out_len, &new_len) ||+ !resize_dirty ((int) new_len)))return false;char *dst = arrayZ + old_len;diff --git a/thirdparty/harfbuzz/src/hb-vector-draw.cc b/thirdparty/harfbuzz/src/hb-vector-draw.ccindex 1a96cb003df..5208fdcf57f 100644--- a/thirdparty/harfbuzz/src/hb-vector-draw.cc+++ b/thirdparty/harfbuzz/src/hb-vector-draw.cc@@ -49,36 +49,90 @@ hb_vector_svg_buffer_contains (const hb_vector_buf_t &buf, const char *needle)/* ---- SVG draw callbacks ---- */static void hb_vector_draw_svg_move_to (hb_draw_funcs_t *, void *dd, hb_draw_state_t *, float x, float y, void *)-{ auto *d = (hb_vector_draw_t *) dd; d->path.append_c ('M'); d->append_xy_svg (x, y); }+{+ auto *d = (hb_vector_draw_t *) dd;+ unsigned before;+ if (unlikely (!d->begin_path_command (&before))) return;+ d->path.append_c ('M'); d->append_xy_svg (x, y);+ d->end_path_command (before);+}static void hb_vector_draw_svg_line_to (hb_draw_funcs_t *, void *dd, hb_draw_state_t *, float x, float y, void *)-{ auto *d = (hb_vector_draw_t *) dd; d->path.append_c ('L'); d->append_xy_svg (x, y); }+{+ auto *d = (hb_vector_draw_t *) dd;+ unsigned before;+ if (unlikely (!d->begin_path_command (&before))) return;+ d->path.append_c ('L'); d->append_xy_svg (x, y);+ d->end_path_command (before);+}static void hb_vector_draw_svg_quadratic_to (hb_draw_funcs_t *, void *dd, hb_draw_state_t *, float cx, float cy, float x, float y, void *)-{ auto *d = (hb_vector_draw_t *) dd; d->path.append_c ('Q'); d->append_xy_svg (cx, cy); d->path.append_c (' '); d->append_xy_svg (x, y); }+{+ auto *d = (hb_vector_draw_t *) dd;+ unsigned before;+ if (unlikely (!d->begin_path_command (&before))) return;+ d->path.append_c ('Q'); d->append_xy_svg (cx, cy); d->path.append_c (' '); d->append_xy_svg (x, y);+ d->end_path_command (before);+}static void hb_vector_draw_svg_cubic_to (hb_draw_funcs_t *, void *dd, hb_draw_state_t *, float c1x, float c1y, float c2x, float c2y, float x, float y, void *)-{ auto *d = (hb_vector_draw_t *) dd; d->path.append_c ('C'); d->append_xy_svg (c1x, c1y); d->path.append_c (' '); d->append_xy_svg (c2x, c2y); d->path.append_c (' '); d->append_xy_svg (x, y); }+{+ auto *d = (hb_vector_draw_t *) dd;+ unsigned before;+ if (unlikely (!d->begin_path_command (&before))) return;+ d->path.append_c ('C'); d->append_xy_svg (c1x, c1y); d->path.append_c (' '); d->append_xy_svg (c2x, c2y); d->path.append_c (' '); d->append_xy_svg (x, y);+ d->end_path_command (before);+}static void hb_vector_draw_svg_close_path (hb_draw_funcs_t *, void *dd, hb_draw_state_t *, void *)-{ ((hb_vector_draw_t *) dd)->path.append_c ('Z'); }+{+ auto *d = (hb_vector_draw_t *) dd;+ unsigned before;+ if (unlikely (!d->begin_path_command (&before))) return;+ d->path.append_c ('Z');+ d->end_path_command (before);+}/* ---- PDF draw callbacks ---- */static void hb_vector_draw_pdf_move_to (hb_draw_funcs_t *, void *dd, hb_draw_state_t *, float x, float y, void *)-{ auto *d = (hb_vector_draw_t *) dd; d->append_xy_pdf (x, y); d->path.append_str (" m\n"); }+{+ auto *d = (hb_vector_draw_t *) dd;+ unsigned before;+ if (unlikely (!d->begin_path_command (&before))) return;+ d->append_xy_pdf (x, y); d->path.append_str (" m\n");+ d->end_path_command (before);+}static void hb_vector_draw_pdf_line_to (hb_draw_funcs_t *, void *dd, hb_draw_state_t *, float x, float y, void *)-{ auto *d = (hb_vector_draw_t *) dd; d->append_xy_pdf (x, y); d->path.append_str (" l\n"); }+{+ auto *d = (hb_vector_draw_t *) dd;+ unsigned before;+ if (unlikely (!d->begin_path_command (&before))) return;+ d->append_xy_pdf (x, y); d->path.append_str (" l\n");+ d->end_path_command (before);+}/* No quadratic_to — null fallback auto-promotes to cubic. */static void hb_vector_draw_pdf_cubic_to (hb_draw_funcs_t *, void *dd, hb_draw_state_t *, float c1x, float c1y, float c2x, float c2y, float x, float y, void *)-{ auto *d = (hb_vector_draw_t *) dd; d->append_xy_pdf (c1x, c1y); d->path.append_c (' '); d->append_xy_pdf (c2x, c2y); d->path.append_c (' '); d->append_xy_pdf (x, y); d->path.append_str (" c\n"); }+{+ auto *d = (hb_vector_draw_t *) dd;+ unsigned before;+ if (unlikely (!d->begin_path_command (&before))) return;+ d->append_xy_pdf (c1x, c1y); d->path.append_c (' '); d->append_xy_pdf (c2x, c2y); d->path.append_c (' '); d->append_xy_pdf (x, y); d->path.append_str (" c\n");+ d->end_path_command (before);+}static void hb_vector_draw_pdf_close_path (hb_draw_funcs_t *, void *dd, hb_draw_state_t *, void *)-{ ((hb_vector_draw_t *) dd)->path.append_str ("h\n"); }+{+ auto *d = (hb_vector_draw_t *) dd;+ unsigned before;+ if (unlikely (!d->begin_path_command (&before))) return;+ d->path.append_str ("h\n");+ d->end_path_command (before);+}/* ---- Lazy loaders ---- */@@ -895,6 +949,7 @@ hb_vector_draw_clear (hb_vector_draw_t *draw)draw->defs.clear ();draw->body.clear ();draw->path.clear ();+ draw->work_left = HB_VECTOR_MAX_DRAW_WORK;}/**diff --git a/thirdparty/harfbuzz/src/hb-vector-draw.hh b/thirdparty/harfbuzz/src/hb-vector-draw.hhindex 0158cfd4197..6f21a32bd9e 100644--- a/thirdparty/harfbuzz/src/hb-vector-draw.hh+++ b/thirdparty/harfbuzz/src/hb-vector-draw.hh@@ -54,6 +54,27 @@ struct hb_vector_draw_thb_vector_buf_t pdf_extgstate_dict;unsigned pdf_extgstate_count = 0;+ /* Cumulative output budget for the current draw session; reset by+ * hb_vector_draw_clear(). Charge complete path commands so budget+ * exhaustion cannot leave a syntactically partial command. */+ int64_t work_left = HB_VECTOR_MAX_DRAW_WORK;++ bool begin_path_command (unsigned *before)+ {+ if (unlikely (work_left <= 0 || path.in_error ()))+ return false;+ *before = path.length;+ return true;+ }++ void end_path_command (unsigned before)+ {+ if (unlikely (path.in_error ()))+ work_left = 0;+ else+ work_left -= path.length - before;+ }+void set_precision (unsigned p){p = hb_min (p, 12u);diff --git a/thirdparty/harfbuzz/src/hb-vector-paint-pdf.cc b/thirdparty/harfbuzz/src/hb-vector-paint-pdf.ccindex 64b52e421d9..69a522c86ba 100644--- a/thirdparty/harfbuzz/src/hb-vector-paint-pdf.cc+++ b/thirdparty/harfbuzz/src/hb-vector-paint-pdf.cc@@ -339,12 +339,18 @@ hb_pdf_emit_glyph_path (hb_vector_paint_t *paint,hb_codepoint_t glyph,hb_vector_buf_t *buf){- hb_vector_path_sink_t sink = {&paint->path, paint->get_precision (),- paint->x_scale_factor, paint->y_scale_factor};paint->path.clear ();- hb_font_draw_glyph (font, glyph,- hb_vector_pdf_path_draw_funcs_get (),- &sink);+ /* Skip the outline extraction when the session work budget is+ * spent; an empty path keeps the document structure intact. */+ if (likely (paint->work_left > 0))+ {+ hb_vector_path_sink_t sink = {&paint->path, paint->get_precision (),+ paint->x_scale_factor, paint->y_scale_factor,+ &paint->work_left};+ hb_font_draw_glyph (font, glyph,+ hb_vector_pdf_path_draw_funcs_get (),+ &sink);+ }buf->append_len (paint->path.arrayZ, paint->path.length);paint->path.clear ();}@@ -392,6 +398,58 @@ hb_pdf_paint_pop_transform (hb_paint_funcs_t *,paint->current_body ().append_str ("Q\n");}+static void+hb_pdf_paint_fill_glyph (hb_paint_funcs_t *,+ void *paint_data,+ hb_codepoint_t glyph,+ hb_font_t *font,+ hb_bool_t,+ hb_color_t c,+ void *)+{+ auto *paint = (hb_vector_paint_t *) paint_data;+ if (unlikely (!paint->ensure_initialized ()))+ return;++ float r = hb_color_get_red (c) / 255.f;+ float g = hb_color_get_green (c) / 255.f;+ float b = hb_color_get_blue (c) / 255.f;+ float a = hb_color_get_alpha (c) / 255.f;++ if (a < 1.f / 255.f)+ return;++ auto &body = paint->current_body ();++ bool scoped = false;+ /* Set alpha via ExtGState if needed, scoped so it does not leak+ * into later paints. */+ if (a < 1.f - 1.f / 512.f)+ {+ auto *res = hb_pdf_get_resources (paint);+ if (res)+ {+ unsigned gs_idx = res->add_extgstate_alpha (a);+ body.append_str ("q\n");+ scoped = true;+ body.append_str ("/GS");+ body.append_unsigned (gs_idx);+ body.append_str (" gs\n");+ }+ }++ body.append_num (r, 4);+ body.append_c (' ');+ body.append_num (g, 4);+ body.append_c (' ');+ body.append_num (b, 4);+ body.append_str (" rg\n");+ hb_pdf_emit_glyph_path (paint, font, glyph, &body);+ body.append_str ("f\n");+ if (scoped)+ body.append_str ("Q\n");+}+static voidhb_pdf_paint_push_clip_glyph (hb_paint_funcs_t *,void *paint_data,@@ -453,7 +511,8 @@ hb_pdf_paint_push_clip_path_start (hb_paint_funcs_t *,* scale_factor so they land in output space. */paint->clip_path_sink = {&body, paint->get_precision (),paint->x_scale_factor,- paint->y_scale_factor};+ paint->y_scale_factor,+ &paint->work_left};*draw_data = &paint->clip_path_sink;return hb_vector_pdf_path_draw_funcs_get ();}@@ -546,8 +605,19 @@ hb_pdf_build_indexed_smask (hb_vector_buf_t *out,(void) width; (void) height; (void) trns; (void) trns_len;return false;#else+ /* Guard the size arithmetic below against 32-bit overflow. width/height come+ * from the attacker-controlled PNG IHDR; without this, (width + 1) * height or+ * width * height can wrap and under-size buffers that are then indexed per+ * pixel (raw + y * (width + 1), out->arrayZ[y * width + x]). */+ unsigned raw_len, mask_len;+ if (!width || !height ||+ width == 0xFFFFFFFFu ||+ hb_unsigned_mul_overflows (width + 1, height, &raw_len) ||+ hb_unsigned_mul_overflows (width, height, &mask_len))+ return false;+/* Decompress IDAT (zlib). */- unsigned raw_len = (width + 1) * height; /* 1 filter byte per row + width bytes */+ /* raw_len = (width + 1) * height: 1 filter byte per row + width bytes. */uint8_t *raw = (uint8_t *) hb_malloc (raw_len);if (!raw) return false;HB_SCOPE_GUARD (hb_free (raw));@@ -567,7 +637,7 @@ hb_pdf_build_indexed_smask (hb_vector_buf_t *out,return false;/* Un-filter and map to alpha. */- if (!out->resize (width * height))+ if (!out->resize (mask_len))return false;uint8_t *unfiltered = (uint8_t *) hb_malloc (width);@@ -680,11 +750,14 @@ hb_pdf_paint_image (hb_paint_funcs_t *,hb_vector_buf_t idat;unsigned pos = 8;- while (pos + 12 <= len)+ /* Invariant: pos <= len (len >= 8 checked above). All bounds checks below+ * are written to avoid 32-bit wrapping: a malicious chunk_len must not be+ * able to wrap pos + 12 + chunk_len past the end of the buffer. */+ while (len - pos >= 12){uint32_t chunk_len = hb_pdf_png_u32 (data + pos);uint32_t chunk_type = hb_pdf_png_u32 (data + pos + 4);- if (pos + 12 + chunk_len > len)+ if (chunk_len > len - pos - 12)break;const uint8_t *chunk_data = data + pos + 8;@@ -746,7 +819,7 @@ hb_pdf_paint_image (hb_paint_funcs_t *,float ix = (float) extents->x_bearing;float iy = (float) extents->y_bearing + (float) extents->height;float iw = (float) extents->width;- float ih = (float) -extents->height; /* negative because image Y goes up but height is negative in extents */+ float ih = -(float) extents->height; /* negative because image Y goes up but height is negative in extents */body.append_num (paint->sx (iw));body.append_str (" 0 0 ");@@ -892,7 +965,7 @@ hb_pdf_build_gradient_function_from_stops (hb_pdf_resources_t *res,/* Sort by offset. */paint->color_stops_scratch.as_array ().qsort ([] (const hb_color_stop_t &a, const hb_color_stop_t &b)- { return a.offset < b.offset; });+ { return (a.offset > b.offset) - (a.offset < b.offset); });if (count == 2){@@ -1303,6 +1376,7 @@ hb_pdf_add_sweep_patch (hb_vector_buf_t *mesh,/* Callback context + trampoline for hb_paint_sweep_gradient_tiles. */struct hb_pdf_sweep_ctx_t {+ hb_vector_paint_t *paint;hb_vector_buf_t *mesh;hb_vector_buf_t *alpha_mesh;float cx, cy, xlo, xhi, ylo, yhi;@@ -1314,10 +1388,21 @@ hb_pdf_sweep_emit_patch (float a0, hb_color_t c0,void *user_data){auto *ctx = (hb_pdf_sweep_ctx_t *) user_data;+ auto *paint = ctx->paint;+ /* Skip patch generation when the session work budget is spent, so+ * per-gradient patch counts cannot multiply with the paint-graph+ * traversal limits of the font tables driving us. */+ if (unlikely (paint->work_left <= 0))+ return;+ unsigned before = ctx->mesh->length ++ (ctx->alpha_mesh ? ctx->alpha_mesh->length : 0);hb_pdf_add_sweep_patch (ctx->mesh, ctx->alpha_mesh,ctx->cx, ctx->cy,ctx->xlo, ctx->xhi, ctx->ylo, ctx->yhi,a0, c0, a1, c1);+ unsigned after = ctx->mesh->length ++ (ctx->alpha_mesh ? ctx->alpha_mesh->length : 0);+ paint->work_left -= after - before;}static void@@ -1342,7 +1427,7 @@ hb_pdf_paint_sweep_gradient (hb_paint_funcs_t *,hb_vector_t<hb_color_stop_t> &stops = paint->color_stops_scratch;stops.as_array ().qsort ([] (const hb_color_stop_t &a, const hb_color_stop_t &b)- { return a.offset < b.offset; });+ { return (a.offset > b.offset) - (a.offset < b.offset); });hb_paint_extend_t extend = hb_color_line_get_extend (color_line);@@ -1359,7 +1444,7 @@ hb_pdf_paint_sweep_gradient (hb_paint_funcs_t *,if (needs_alpha)alpha_mesh.alloc (256);- hb_pdf_sweep_ctx_t ctx { &mesh, needs_alpha ? &alpha_mesh : nullptr,+ hb_pdf_sweep_ctx_t ctx { paint, &mesh, needs_alpha ? &alpha_mesh : nullptr,scx, scy, xlo, xhi, ylo, yhi };hb_paint_sweep_gradient_tiles (stops.arrayZ, stops.length, extend,start_angle, end_angle,@@ -1520,6 +1605,7 @@ static struct hb_pdf_paint_funcs_lazy_loader_thb_paint_funcs_t *funcs = hb_paint_funcs_create ();hb_paint_funcs_set_push_transform_func (funcs, (hb_paint_push_transform_func_t) hb_pdf_paint_push_transform, nullptr, nullptr);hb_paint_funcs_set_pop_transform_func (funcs, (hb_paint_pop_transform_func_t) hb_pdf_paint_pop_transform, nullptr, nullptr);+ hb_paint_funcs_set_fill_glyph_func (funcs, (hb_paint_fill_glyph_func_t) hb_pdf_paint_fill_glyph, nullptr, nullptr);hb_paint_funcs_set_push_clip_glyph_func (funcs, (hb_paint_push_clip_glyph_func_t) hb_pdf_paint_push_clip_glyph, nullptr, nullptr);hb_paint_funcs_set_push_clip_rectangle_func (funcs, (hb_paint_push_clip_rectangle_func_t) hb_pdf_paint_push_clip_rectangle, nullptr, nullptr);hb_paint_funcs_set_push_clip_path_start_func (funcs, (hb_paint_push_clip_path_start_func_t) hb_pdf_paint_push_clip_path_start, nullptr, nullptr);@@ -1598,11 +1684,11 @@ hb_vector_paint_render_pdf (hb_vector_paint_t *paint)out.append_str ("3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [");out.append_num (ex);out.append_c (' ');- out.append_num (-(ey + eh));+ out.append_num (ey);out.append_c (' ');out.append_num (ex + ew);out.append_c (' ');- out.append_num (-ey);+ out.append_num (ey + eh);out.append_str ("]\n/Contents 4 0 R");/* Resources. */@@ -1660,7 +1746,7 @@ hb_vector_paint_render_pdf (hb_vector_paint_t *paint)bg_prefix.append_str (" rg\n");bg_prefix.append_num (ex);bg_prefix.append_c (' ');- bg_prefix.append_num (-(ey + eh));+ bg_prefix.append_num (ey);bg_prefix.append_c (' ');bg_prefix.append_num (ew);bg_prefix.append_c (' ');diff --git a/thirdparty/harfbuzz/src/hb-vector-paint-svg.cc b/thirdparty/harfbuzz/src/hb-vector-paint-svg.ccindex eca53e39a6b..e8b9f4456cb 100644--- a/thirdparty/harfbuzz/src/hb-vector-paint-svg.cc+++ b/thirdparty/harfbuzz/src/hb-vector-paint-svg.cc@@ -246,6 +246,7 @@ hb_vector_svg_add_sweep_patch (hb_vector_buf_t *body,/* Callback context + trampoline for hb_paint_sweep_gradient_tiles. */struct hb_vector_svg_sweep_ctx_t{+ hb_vector_paint_t *paint;hb_vector_buf_t *body;unsigned precision;float cx, cy, radius;@@ -257,10 +258,18 @@ hb_vector_svg_sweep_emit_patch (float a0, hb_color_t c0,void *user_data){auto *ctx = (hb_vector_svg_sweep_ctx_t *) user_data;+ auto *paint = ctx->paint;+ /* Skip patch generation when the session work budget is spent, so+ * per-gradient patch counts cannot multiply with the paint-graph+ * traversal limits of the font tables driving us. */+ if (unlikely (paint->work_left <= 0))+ return;+ unsigned before = ctx->body->length;hb_vector_svg_add_sweep_patch (ctx->body, ctx->precision,ctx->cx, ctx->cy, ctx->radius,a0, hb_vector_svg_rgba_from_hb_color (c0),a1, hb_vector_svg_rgba_from_hb_color (c1));+ paint->work_left -= ctx->body->length - before;}@@ -268,6 +277,7 @@ static void hb_vector_paint_push_transform (hb_paint_funcs_t *, void *,float, float, float, float, float, float,void *);static void hb_vector_paint_pop_transform (hb_paint_funcs_t *, void *, void *);+static void hb_vector_paint_fill_glyph (hb_paint_funcs_t *, void *, hb_codepoint_t, hb_font_t *, hb_bool_t, hb_color_t, void *);static void hb_vector_paint_push_clip_glyph (hb_paint_funcs_t *, void *, hb_codepoint_t, hb_font_t *, void *);static void hb_vector_paint_push_clip_rectangle (hb_paint_funcs_t *, void *, float, float, float, float, void *);static hb_draw_funcs_t * hb_vector_paint_push_clip_path_start (hb_paint_funcs_t *, void *, void **, void *);@@ -308,6 +318,7 @@ static struct hb_vector_paint_funcs_lazy_loader_thb_paint_funcs_t *funcs = hb_paint_funcs_create ();hb_paint_funcs_set_push_transform_func (funcs, (hb_paint_push_transform_func_t) hb_vector_paint_push_transform, nullptr, nullptr);hb_paint_funcs_set_pop_transform_func (funcs, (hb_paint_pop_transform_func_t) hb_vector_paint_pop_transform, nullptr, nullptr);+ hb_paint_funcs_set_fill_glyph_func (funcs, (hb_paint_fill_glyph_func_t) hb_vector_paint_fill_glyph, nullptr, nullptr);hb_paint_funcs_set_push_clip_glyph_func (funcs, (hb_paint_push_clip_glyph_func_t) hb_vector_paint_push_clip_glyph, nullptr, nullptr);hb_paint_funcs_set_push_clip_rectangle_func (funcs, (hb_paint_push_clip_rectangle_func_t) hb_vector_paint_push_clip_rectangle, nullptr, nullptr);hb_paint_funcs_set_push_clip_path_start_func (funcs, (hb_paint_push_clip_path_start_func_t) hb_vector_paint_push_clip_path_start, nullptr, nullptr);@@ -413,6 +424,38 @@ hb_vector_paint_pop_transform (hb_paint_funcs_t *,paint->current_body ().append_str ("</g>\n");}+static void+hb_vector_paint_fill_glyph (hb_paint_funcs_t *,+ void *paint_data,+ hb_codepoint_t glyph,+ hb_font_t *font,+ hb_bool_t,+ hb_color_t color,+ void *)+{+ auto *paint = (hb_vector_paint_t *) paint_data;+ if (unlikely (!paint->ensure_initialized ()))+ return;++ paint->path.clear ();+ /* Skip the outline extraction when the session work budget is+ * spent; an empty path keeps the document structure intact. */+ if (likely (paint->work_left > 0))+ {+ hb_vector_path_sink_t sink = {&paint->path, paint->get_precision (),+ paint->x_scale_factor, paint->y_scale_factor,+ &paint->work_left};+ hb_font_draw_glyph (font, glyph, hb_vector_svg_path_draw_funcs_get (), &sink);+ }++ auto &body = paint->current_body ();+ body.append_str ("<path d=\"");+ body.append_len (paint->path.arrayZ, paint->path.length);+ body.append_str ("\" fill=\"");+ body.append_svg_color (color, true);+ body.append_str ("\"/>\n");+}+static voidhb_vector_paint_push_clip_glyph (hb_paint_funcs_t *,void *paint_data,@@ -428,9 +471,13 @@ hb_vector_paint_push_clip_glyph (hb_paint_funcs_t *,unsigned pfx_len = paint->id_prefix_length;paint->path.clear ();+ /* Skip the outline extraction when the session work budget is+ * spent; an empty clip path clips everything out. */+ if (likely (paint->work_left > 0)){hb_vector_path_sink_t sink = {&paint->path, paint->get_precision (),- paint->x_scale_factor, paint->y_scale_factor};+ paint->x_scale_factor, paint->y_scale_factor,+ &paint->work_left};hb_font_draw_glyph (font, glyph, hb_vector_svg_path_draw_funcs_get (), &sink);}@@ -510,7 +557,8 @@ hb_vector_paint_push_clip_path_start (hb_paint_funcs_t *,paint->path.clear ();paint->clip_path_sink = {&paint->path, paint->get_precision (),paint->x_scale_factor,- paint->y_scale_factor};+ paint->y_scale_factor,+ &paint->work_left};*draw_data = &paint->clip_path_sink;return hb_vector_svg_path_draw_funcs_get ();}@@ -781,7 +829,7 @@ hb_vector_paint_sweep_gradient (hb_paint_funcs_t *,float ga1 = start_angle + mx * (end_angle - start_angle);hb_vector_svg_sweep_ctx_t ctx {- &paint->current_body (), paint->get_precision (), paint->sx (cx), paint->sy (cy), 32767.f+ paint, &paint->current_body (), paint->get_precision (), paint->sx (cx), paint->sy (cy), 32767.f};hb_paint_sweep_gradient_tiles (stops.arrayZ, stops.length,hb_color_line_get_extend (color_line),diff --git a/thirdparty/harfbuzz/src/hb-vector-paint.cc b/thirdparty/harfbuzz/src/hb-vector-paint.ccindex 5d66c2ac65b..92a1de35a81 100644--- a/thirdparty/harfbuzz/src/hb-vector-paint.cc+++ b/thirdparty/harfbuzz/src/hb-vector-paint.cc@@ -744,6 +744,7 @@ hb_vector_paint_clear (hb_vector_paint_t *paint)paint->transform_group_overflow_depth = 0;paint->clip_rect_counter = 0;paint->clip_path_counter = 0;+ paint->work_left = HB_VECTOR_MAX_PAINT_WORK;paint->gradient_counter = 0;paint->color_glyph_depth = 0;paint->path_def_count = 0;diff --git a/thirdparty/harfbuzz/src/hb-vector-paint.hh b/thirdparty/harfbuzz/src/hb-vector-paint.hhindex 1bc7d8776a3..fecb4a0a3c6 100644--- a/thirdparty/harfbuzz/src/hb-vector-paint.hh+++ b/thirdparty/harfbuzz/src/hb-vector-paint.hh@@ -65,7 +65,14 @@ struct hb_vector_paint_tunsigned clip_rect_counter = 0;unsigned clip_path_counter = 0;- hb_vector_path_sink_t clip_path_sink = {nullptr, 0, 1.f, 1.f};+ /* Cumulative work budget for the current paint session; reset by+ * hb_vector_paint_clear(). Charged with the bytes of path data+ * generated by each glyph-outline extraction and of sweep-gradient+ * patch data, so per-glyph and per-gradient limits cannot multiply+ * with the paint-graph traversal limits of the font tables driving+ * us (e.g. COLR). */+ int64_t work_left = HB_VECTOR_MAX_PAINT_WORK;+ hb_vector_path_sink_t clip_path_sink = {nullptr, 0, 1.f, 1.f, nullptr};unsigned gradient_counter = 0;unsigned color_glyph_depth = 0;unsigned path_def_count = 0;diff --git a/thirdparty/harfbuzz/src/hb-vector-path.cc b/thirdparty/harfbuzz/src/hb-vector-path.ccindex e63726873d2..db66e12a788 100644--- a/thirdparty/harfbuzz/src/hb-vector-path.cc+++ b/thirdparty/harfbuzz/src/hb-vector-path.cc@@ -48,8 +48,11 @@ hb_vector_svg_path_move_to (hb_draw_funcs_t *, void *draw_data, hb_draw_state_tfloat to_x, float to_y, void *){auto *s = (hb_vector_path_sink_t *) draw_data;+ unsigned before;+ if (unlikely (!s->begin_command (&before))) return;s->path->append_c ('M');hb_vector_svg_path_append_xy (s, to_x, to_y);+ s->end_command (before);}static void@@ -57,8 +60,11 @@ hb_vector_svg_path_line_to (hb_draw_funcs_t *, void *draw_data, hb_draw_state_tfloat to_x, float to_y, void *){auto *s = (hb_vector_path_sink_t *) draw_data;+ unsigned before;+ if (unlikely (!s->begin_command (&before))) return;s->path->append_c ('L');hb_vector_svg_path_append_xy (s, to_x, to_y);+ s->end_command (before);}static void@@ -66,10 +72,13 @@ hb_vector_svg_path_quadratic_to (hb_draw_funcs_t *, void *draw_data, hb_draw_stafloat cx, float cy, float to_x, float to_y, void *){auto *s = (hb_vector_path_sink_t *) draw_data;+ unsigned before;+ if (unlikely (!s->begin_command (&before))) return;s->path->append_c ('Q');hb_vector_svg_path_append_xy (s, cx, cy);s->path->append_c (' ');hb_vector_svg_path_append_xy (s, to_x, to_y);+ s->end_command (before);}static void@@ -78,19 +87,25 @@ hb_vector_svg_path_cubic_to (hb_draw_funcs_t *, void *draw_data, hb_draw_state_tfloat to_x, float to_y, void *){auto *s = (hb_vector_path_sink_t *) draw_data;+ unsigned before;+ if (unlikely (!s->begin_command (&before))) return;s->path->append_c ('C');hb_vector_svg_path_append_xy (s, c1x, c1y);s->path->append_c (' ');hb_vector_svg_path_append_xy (s, c2x, c2y);s->path->append_c (' ');hb_vector_svg_path_append_xy (s, to_x, to_y);+ s->end_command (before);}static voidhb_vector_svg_path_close_path (hb_draw_funcs_t *, void *draw_data, hb_draw_state_t *, void *){auto *s = (hb_vector_path_sink_t *) draw_data;+ unsigned before;+ if (unlikely (!s->begin_command (&before))) return;s->path->append_c ('Z');+ s->end_command (before);}@@ -109,8 +124,11 @@ hb_vector_pdf_path_move_to (hb_draw_funcs_t *, void *draw_data, hb_draw_state_tfloat to_x, float to_y, void *){auto *s = (hb_vector_path_sink_t *) draw_data;+ unsigned before;+ if (unlikely (!s->begin_command (&before))) return;hb_vector_pdf_path_append_xy (s, to_x, to_y);s->path->append_str (" m\n");+ s->end_command (before);}static void@@ -118,8 +136,11 @@ hb_vector_pdf_path_line_to (hb_draw_funcs_t *, void *draw_data, hb_draw_state_tfloat to_x, float to_y, void *){auto *s = (hb_vector_path_sink_t *) draw_data;+ unsigned before;+ if (unlikely (!s->begin_command (&before))) return;hb_vector_pdf_path_append_xy (s, to_x, to_y);s->path->append_str (" l\n");+ s->end_command (before);}/* No quadratic_to — the null fallback auto-promotes to cubic. */@@ -130,19 +151,25 @@ hb_vector_pdf_path_cubic_to (hb_draw_funcs_t *, void *draw_data, hb_draw_state_tfloat to_x, float to_y, void *){auto *s = (hb_vector_path_sink_t *) draw_data;+ unsigned before;+ if (unlikely (!s->begin_command (&before))) return;hb_vector_pdf_path_append_xy (s, c1x, c1y);s->path->append_c (' ');hb_vector_pdf_path_append_xy (s, c2x, c2y);s->path->append_c (' ');hb_vector_pdf_path_append_xy (s, to_x, to_y);s->path->append_str (" c\n");+ s->end_command (before);}static voidhb_vector_pdf_path_close_path (hb_draw_funcs_t *, void *draw_data, hb_draw_state_t *, void *){auto *s = (hb_vector_path_sink_t *) draw_data;+ unsigned before;+ if (unlikely (!s->begin_command (&before))) return;s->path->append_str ("h\n");+ s->end_command (before);}diff --git a/thirdparty/harfbuzz/src/hb-vector-path.hh b/thirdparty/harfbuzz/src/hb-vector-path.hhindex 9936428d3dc..8618a5b82c8 100644--- a/thirdparty/harfbuzz/src/hb-vector-path.hh+++ b/thirdparty/harfbuzz/src/hb-vector-path.hh@@ -44,6 +44,25 @@ struct hb_vector_path_sink_tunsigned precision;float x_scale;float y_scale;+ int64_t *work_left;++ bool begin_command (unsigned *before)+ {+ if (unlikely (path->in_error () ||+ (work_left && *work_left <= 0)))+ return false;+ *before = path->length;+ return true;+ }++ void end_command (unsigned before)+ {+ if (!work_left) return;+ if (unlikely (path->in_error ()))+ *work_left = 0;+ else+ *work_left -= path->length - before;+ }};HB_INTERNAL hb_draw_funcs_t *diff --git a/thirdparty/harfbuzz/src/hb-vector.hh b/thirdparty/harfbuzz/src/hb-vector.hhindex e831c72b469..9f742398c39 100644--- a/thirdparty/harfbuzz/src/hb-vector.hh+++ b/thirdparty/harfbuzz/src/hb-vector.hh@@ -272,7 +272,7 @@ struct hb_vector_tconst Type& tail () const { return (*this)[length - 1]; }explicit operator bool () const { return length; }- size_t get_size () const { return length * item_size; }+ size_t get_size () const { return hb_unsigned_mul_saturate (length, item_size); }/* Sink interface. */template <typename T>@@ -635,7 +635,9 @@ struct hb_vector_tHB_ALWAYS_INLINE_VECTOR_ALLOCSbool resize_full (int size_, bool initialize, bool exact){- unsigned int size = size_ < 0 ? 0u : (unsigned int) size_;+ if (unlikely (size_ < 0))+ return false;+ unsigned int size = (unsigned int) size_;if (!alloc (size, exact))return false;diff --git a/thirdparty/harfbuzz/src/hb-version.h b/thirdparty/harfbuzz/src/hb-version.hindex f44973e60da..10aed673158 100644--- a/thirdparty/harfbuzz/src/hb-version.h+++ b/thirdparty/harfbuzz/src/hb-version.h@@ -47,7 +47,7 @@ HB_BEGIN_DECLS** The minor component of the library version available at compile-time.*/-#define HB_VERSION_MINOR 2+#define HB_VERSION_MINOR 4/*** HB_VERSION_MICRO:*@@ -60,7 +60,7 @@ HB_BEGIN_DECLS** A string literal containing the library version available at compile-time.*/-#define HB_VERSION_STRING "14.2.0"+#define HB_VERSION_STRING "14.4.0"/*** HB_VERSION_ATLEAST:diff --git a/thirdparty/harfbuzz/src/hb.hh b/thirdparty/harfbuzz/src/hb.hhindex 7e2837f99ab..27f400a8e7b 100644--- a/thirdparty/harfbuzz/src/hb.hh+++ b/thirdparty/harfbuzz/src/hb.hh@@ -151,6 +151,7 @@#pragma GCC diagnostic ignored "-Wrange-loop-analysis" // https://github.com/harfbuzz/harfbuzz/issues/2834#pragma GCC diagnostic ignored "-Wstrict-aliasing"#pragma GCC diagnostic ignored "-Wtype-limits"+#pragma GCC diagnostic ignored "-Wunused-template"#pragma GCC diagnostic ignored "-Wc++11-compat" // only gcc raises it#endif@@ -203,6 +204,7 @@#define HB_OT_H_IN#include "hb-aat.h"#define HB_AAT_H_IN+#define HB_SUBSET_H_IN#include <cassert>#include <cfloat>@@ -279,7 +281,7 @@#if defined(__GNUC__) && (__GNUC__ >= 4) || (__clang__)#define HB_UNUSED __attribute__((unused))#elif defined(_MSC_VER) /* https://github.com/harfbuzz/harfbuzz/issues/635 */-#define HB_UNUSED __pragma(warning(suppress: 4100 4101))+#define HB_UNUSED __pragma(warning(suppress: 4100 4101 4189))#else#define HB_UNUSED#endif@@ -327,6 +329,14 @@#endif#endif+#ifndef HB_NEVER_INLINE+#if defined(_MSC_VER)+#define HB_NEVER_INLINE __declspec(noinline)+#else+#define HB_NEVER_INLINE __attribute__((noinline))+#endif+#endif+#ifndef HB_HOT#define HB_HOT __attribute__((hot))#endif@@ -375,16 +385,6 @@# define HB_NODISCARD#endif-/* https://github.com/harfbuzz/harfbuzz/issues/1852 */-#if defined(__clang__) && !(defined(_AIX) && (defined(__IBMCPP__) || defined(__ibmxl__)))-/* Disable certain sanitizer errors. */-/* https://github.com/harfbuzz/harfbuzz/issues/1247 */-#define HB_NO_SANITIZE_SIGNED_INTEGER_OVERFLOW __attribute__((no_sanitize("signed-integer-overflow")))-#else-#define HB_NO_SANITIZE_SIGNED_INTEGER_OVERFLOW-#endif--#ifdef _WIN32/* We need Windows Vista for both Uniscribe backend and for* MemoryBarrier. We don't support compiling on Windows XP,