xref: /aosp_15_r20/external/harfbuzz_ng/src/hb-ot-var-fvar-table.hh (revision 2d1272b857b1f7575e6e246373e1cb218663db8a)
1 /*
2  * Copyright © 2017  Google, Inc.
3  *
4  *  This is part of HarfBuzz, a text shaping library.
5  *
6  * Permission is hereby granted, without written agreement and without
7  * license or royalty fees, to use, copy, modify, and distribute this
8  * software and its documentation for any purpose, provided that the
9  * above copyright notice and the following two paragraphs appear in
10  * all copies of this software.
11  *
12  * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
13  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
14  * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
15  * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
16  * DAMAGE.
17  *
18  * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
19  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20  * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
21  * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
22  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
23  *
24  * Google Author(s): Behdad Esfahbod
25  */
26 
27 #ifndef HB_OT_VAR_FVAR_TABLE_HH
28 #define HB_OT_VAR_FVAR_TABLE_HH
29 
30 #include "hb-open-type.hh"
31 
32 /*
33  * fvar -- Font Variations
34  * https://docs.microsoft.com/en-us/typography/opentype/spec/fvar
35  */
36 
37 #define HB_OT_TAG_fvar HB_TAG('f','v','a','r')
38 
39 
40 namespace OT {
41 
axis_coord_pinned_or_within_axis_range(const hb_array_t<const F16DOT16> coords,unsigned axis_index,Triple axis_limit)42 static bool axis_coord_pinned_or_within_axis_range (const hb_array_t<const F16DOT16> coords,
43                                                     unsigned axis_index,
44                                                     Triple axis_limit)
45 {
46   double axis_coord = static_cast<double>(coords[axis_index].to_float ());
47   if (axis_limit.is_point ())
48   {
49     if (axis_limit.minimum != axis_coord)
50       return false;
51   }
52   else
53   {
54     if (axis_coord < axis_limit.minimum ||
55         axis_coord > axis_limit.maximum)
56       return false;
57   }
58   return true;
59 }
60 
61 struct InstanceRecord
62 {
63   friend struct fvar;
64 
get_coordinatesOT::InstanceRecord65   hb_array_t<const F16DOT16> get_coordinates (unsigned int axis_count) const
66   { return coordinatesZ.as_array (axis_count); }
67 
keep_instanceOT::InstanceRecord68   bool keep_instance (unsigned axis_count,
69                       const hb_map_t *axes_index_tag_map,
70                       const hb_hashmap_t<hb_tag_t, Triple> *axes_location) const
71   {
72     if (axes_location->is_empty ()) return true;
73     const hb_array_t<const F16DOT16> coords = get_coordinates (axis_count);
74     for (unsigned i = 0 ; i < axis_count; i++)
75     {
76       uint32_t *axis_tag;
77       if (!axes_index_tag_map->has (i, &axis_tag))
78         return false;
79       if (!axes_location->has (*axis_tag))
80         continue;
81 
82       Triple axis_limit = axes_location->get (*axis_tag);
83       if (!axis_coord_pinned_or_within_axis_range (coords, i, axis_limit))
84         return false;
85     }
86     return true;
87   }
88 
subsetOT::InstanceRecord89   bool subset (hb_subset_context_t *c,
90                unsigned axis_count,
91                bool has_postscript_nameid) const
92   {
93     TRACE_SUBSET (this);
94     if (unlikely (!c->serializer->embed (subfamilyNameID))) return_trace (false);
95     if (unlikely (!c->serializer->embed (flags))) return_trace (false);
96 
97     const hb_array_t<const F16DOT16> coords = get_coordinates (axis_count);
98     const hb_hashmap_t<hb_tag_t, Triple> *axes_location = &c->plan->user_axes_location;
99     for (unsigned i = 0 ; i < axis_count; i++)
100     {
101       uint32_t *axis_tag;
102       Triple *axis_limit;
103       // only keep instances whose coordinates == pinned axis location
104       if (!c->plan->axes_old_index_tag_map.has (i, &axis_tag)) return_trace (false);
105       if (axes_location->has (*axis_tag, &axis_limit))
106       {
107         if (!axis_coord_pinned_or_within_axis_range (coords, i, *axis_limit))
108           return_trace (false);
109 
110         //skip pinned axis
111         if (axis_limit->is_point ())
112           continue;
113       }
114 
115       if (!c->serializer->embed (coords[i]))
116         return_trace (false);
117     }
118 
119     if (has_postscript_nameid)
120     {
121       NameID name_id;
122       name_id = StructAfter<NameID> (coords);
123       if (!c->serializer->embed (name_id))
124         return_trace (false);
125     }
126 
127     return_trace (true);
128   }
129 
sanitizeOT::InstanceRecord130   bool sanitize (hb_sanitize_context_t *c, unsigned int axis_count) const
131   {
132     TRACE_SANITIZE (this);
133     return_trace (c->check_struct (this) &&
134 		  hb_barrier () &&
135 		  c->check_array (coordinatesZ.arrayZ, axis_count));
136   }
137 
138   protected:
139   NameID	subfamilyNameID;/* The name ID for entries in the 'name' table
140 				 * that provide subfamily names for this instance. */
141   HBUINT16	flags;		/* Reserved for future use — set to 0. */
142   UnsizedArrayOf<F16DOT16>
143 		coordinatesZ;	/* The coordinates array for this instance. */
144   //NameID	postScriptNameIDX;/*Optional. The name ID for entries in the 'name'
145   //				  * table that provide PostScript names for this
146   //				  * instance. */
147 
148   public:
149   DEFINE_SIZE_UNBOUNDED (4);
150 };
151 
152 struct AxisRecord
153 {
cmpOT::AxisRecord154   int cmp (hb_tag_t key) const { return axisTag.cmp (key); }
155 
156   enum
157   {
158     AXIS_FLAG_HIDDEN	= 0x0001,
159   };
160 
161 #ifndef HB_DISABLE_DEPRECATED
get_axis_deprecatedOT::AxisRecord162   void get_axis_deprecated (hb_ot_var_axis_t *info) const
163   {
164     info->tag = axisTag;
165     info->name_id = axisNameID;
166     get_coordinates (info->min_value, info->default_value, info->max_value);
167   }
168 #endif
169 
get_axis_infoOT::AxisRecord170   void get_axis_info (unsigned axis_index, hb_ot_var_axis_info_t *info) const
171   {
172     info->axis_index = axis_index;
173     info->tag = axisTag;
174     info->name_id = axisNameID;
175     info->flags = (hb_ot_var_axis_flags_t) (unsigned int) flags;
176     get_coordinates (info->min_value, info->default_value, info->max_value);
177     info->reserved = 0;
178   }
179 
get_axis_tagOT::AxisRecord180   hb_tag_t get_axis_tag () const { return axisTag; }
181 
normalize_axis_valueOT::AxisRecord182   int normalize_axis_value (float v) const
183   {
184     float min_value, default_value, max_value;
185     get_coordinates (min_value, default_value, max_value);
186 
187     v = hb_clamp (v, min_value, max_value);
188 
189     if (v == default_value)
190       return 0;
191     else if (v < default_value)
192       v = (v - default_value) / (default_value - min_value);
193     else
194       v = (v - default_value) / (max_value - default_value);
195     return roundf (v * 16384.f);
196   }
197 
unnormalize_axis_valueOT::AxisRecord198   float unnormalize_axis_value (int v) const
199   {
200     float min_value, default_value, max_value;
201     get_coordinates (min_value, default_value, max_value);
202 
203     if (v == 0)
204       return default_value;
205     else if (v < 0)
206       return v * (default_value - min_value) / 16384.f + default_value;
207     else
208       return v * (max_value - default_value) / 16384.f + default_value;
209   }
210 
get_name_idOT::AxisRecord211   hb_ot_name_id_t get_name_id () const { return axisNameID; }
212 
sanitizeOT::AxisRecord213   bool sanitize (hb_sanitize_context_t *c) const
214   {
215     TRACE_SANITIZE (this);
216     return_trace (c->check_struct (this));
217   }
218 
get_coordinatesOT::AxisRecord219   void get_coordinates (float &min, float &default_, float &max) const
220   {
221     default_ = defaultValue.to_float ();
222     /* Ensure order, to simplify client math. */
223     min = hb_min (default_, minValue.to_float ());
224     max = hb_max (default_, maxValue.to_float ());
225   }
226 
get_defaultOT::AxisRecord227   float get_default () const
228   {
229     return defaultValue.to_float ();
230   }
231 
get_triple_distancesOT::AxisRecord232   TripleDistances get_triple_distances () const
233   {
234     float min, default_, max;
235     get_coordinates (min, default_, max);
236     return TripleDistances (
237       static_cast<double>(min),
238       static_cast<double>(default_),
239       static_cast<double>(max));
240   }
241 
subsetOT::AxisRecord242   bool subset (hb_subset_context_t *c) const
243   {
244     TRACE_SUBSET (this);
245     auto *out = c->serializer->embed (this);
246     if (unlikely (!out)) return_trace (false);
247 
248     const hb_hashmap_t<hb_tag_t, Triple>& user_axes_location = c->plan->user_axes_location;
249     Triple *axis_limit;
250     if (user_axes_location.has (axisTag, &axis_limit))
251     {
252       out->minValue.set_float (axis_limit->minimum);
253       out->defaultValue.set_float (axis_limit->middle);
254       out->maxValue.set_float (axis_limit->maximum);
255     }
256     return_trace (true);
257   }
258 
259   public:
260   Tag		axisTag;	/* Tag identifying the design variation for the axis. */
261   protected:
262   F16DOT16	minValue;	/* The minimum coordinate value for the axis. */
263   F16DOT16	defaultValue;	/* The default coordinate value for the axis. */
264   F16DOT16	maxValue;	/* The maximum coordinate value for the axis. */
265   public:
266   HBUINT16	flags;		/* Axis flags. */
267   NameID	axisNameID;	/* The name ID for entries in the 'name' table that
268 				 * provide a display name for this axis. */
269 
270   public:
271   DEFINE_SIZE_STATIC (20);
272 };
273 
274 struct fvar
275 {
276   static constexpr hb_tag_t tableTag = HB_OT_TAG_fvar;
277 
has_dataOT::fvar278   bool has_data () const { return version.to_int (); }
279 
sanitizeOT::fvar280   bool sanitize (hb_sanitize_context_t *c) const
281   {
282     TRACE_SANITIZE (this);
283     return_trace (version.sanitize (c) &&
284 		  hb_barrier () &&
285 		  likely (version.major == 1) &&
286 		  c->check_struct (this) &&
287 		  hb_barrier () &&
288 		  axisSize == 20 && /* Assumed in our code. */
289 		  instanceSize >= axisCount * 4 + 4 &&
290 		  get_axes ().sanitize (c) &&
291 		  c->check_range (&StructAfter<InstanceRecord> (get_axes ()),
292 				  instanceCount, instanceSize));
293   }
294 
get_axis_countOT::fvar295   unsigned int get_axis_count () const { return axisCount; }
296 
297 #ifndef HB_DISABLE_DEPRECATED
get_axes_deprecatedOT::fvar298   unsigned int get_axes_deprecated (unsigned int      start_offset,
299 				    unsigned int     *axes_count /* IN/OUT */,
300 				    hb_ot_var_axis_t *axes_array /* OUT */) const
301   {
302     if (axes_count)
303     {
304       hb_array_t<const AxisRecord> arr = get_axes ().sub_array (start_offset, axes_count);
305       for (unsigned i = 0; i < arr.length; ++i)
306 	arr[i].get_axis_deprecated (&axes_array[i]);
307     }
308     return axisCount;
309   }
310 #endif
311 
get_axis_infosOT::fvar312   unsigned int get_axis_infos (unsigned int           start_offset,
313 			       unsigned int          *axes_count /* IN/OUT */,
314 			       hb_ot_var_axis_info_t *axes_array /* OUT */) const
315   {
316     if (axes_count)
317     {
318       hb_array_t<const AxisRecord> arr = get_axes ().sub_array (start_offset, axes_count);
319       for (unsigned i = 0; i < arr.length; ++i)
320 	arr[i].get_axis_info (start_offset + i, &axes_array[i]);
321     }
322     return axisCount;
323   }
324 
325 #ifndef HB_DISABLE_DEPRECATED
326   bool
find_axis_deprecatedOT::fvar327   find_axis_deprecated (hb_tag_t tag, unsigned *axis_index, hb_ot_var_axis_t *info) const
328   {
329     unsigned i;
330     if (!axis_index) axis_index = &i;
331     *axis_index = HB_OT_VAR_NO_AXIS_INDEX;
332     auto axes = get_axes ();
333     return axes.lfind (tag, axis_index) && ((void) axes[*axis_index].get_axis_deprecated (info), true);
334   }
335 #endif
336   bool
find_axis_infoOT::fvar337   find_axis_info (hb_tag_t tag, hb_ot_var_axis_info_t *info) const
338   {
339     unsigned i;
340     auto axes = get_axes ();
341     return axes.lfind (tag, &i) && ((void) axes[i].get_axis_info (i, info), true);
342   }
343 
normalize_axis_valueOT::fvar344   int normalize_axis_value (unsigned int axis_index, float v) const
345   { return get_axes ()[axis_index].normalize_axis_value (v); }
346 
unnormalize_axis_valueOT::fvar347   float unnormalize_axis_value (unsigned int axis_index, int v) const
348   { return get_axes ()[axis_index].unnormalize_axis_value (v); }
349 
get_instance_countOT::fvar350   unsigned int get_instance_count () const { return instanceCount; }
351 
get_instance_subfamily_name_idOT::fvar352   hb_ot_name_id_t get_instance_subfamily_name_id (unsigned int instance_index) const
353   {
354     const InstanceRecord *instance = get_instance (instance_index);
355     if (unlikely (!instance)) return HB_OT_NAME_ID_INVALID;
356     return instance->subfamilyNameID;
357   }
358 
get_instance_postscript_name_idOT::fvar359   hb_ot_name_id_t get_instance_postscript_name_id (unsigned int instance_index) const
360   {
361     const InstanceRecord *instance = get_instance (instance_index);
362     if (unlikely (!instance)) return HB_OT_NAME_ID_INVALID;
363     if (instanceSize >= axisCount * 4 + 6)
364       return StructAfter<NameID> (instance->get_coordinates (axisCount));
365     return HB_OT_NAME_ID_INVALID;
366   }
367 
get_instance_coordsOT::fvar368   unsigned int get_instance_coords (unsigned int  instance_index,
369 				    unsigned int *coords_length, /* IN/OUT */
370 				    float        *coords         /* OUT */) const
371   {
372     const InstanceRecord *instance = get_instance (instance_index);
373     if (unlikely (!instance))
374     {
375       if (coords_length)
376 	*coords_length = 0;
377       return 0;
378     }
379 
380     if (coords_length && *coords_length)
381     {
382       hb_array_t<const F16DOT16> instanceCoords = instance->get_coordinates (axisCount)
383 							 .sub_array (0, coords_length);
384       for (unsigned int i = 0; i < instanceCoords.length; i++)
385 	coords[i] = instanceCoords.arrayZ[i].to_float ();
386     }
387     return axisCount;
388   }
389 
collect_name_idsOT::fvar390   void collect_name_ids (hb_hashmap_t<hb_tag_t, Triple> *user_axes_location,
391 			 hb_map_t *axes_old_index_tag_map,
392 			 hb_set_t *nameids  /* IN/OUT */) const
393   {
394     if (!has_data ()) return;
395 
396     auto axis_records = get_axes ();
397     for (unsigned i = 0 ; i < (unsigned)axisCount; i++)
398     {
399       hb_tag_t axis_tag = axis_records[i].get_axis_tag ();
400       if (user_axes_location->has (axis_tag) &&
401           user_axes_location->get (axis_tag).is_point ())
402         continue;
403 
404       nameids->add (axis_records[i].get_name_id ());
405     }
406 
407     for (unsigned i = 0 ; i < (unsigned)instanceCount; i++)
408     {
409       const InstanceRecord *instance = get_instance (i);
410 
411       if (!instance->keep_instance (axisCount, axes_old_index_tag_map, user_axes_location))
412         continue;
413 
414       nameids->add (instance->subfamilyNameID);
415 
416       if (instanceSize >= axisCount * 4 + 6)
417       {
418         unsigned post_script_name_id = StructAfter<NameID> (instance->get_coordinates (axisCount));
419         if (post_script_name_id != HB_OT_NAME_ID_INVALID) nameids->add (post_script_name_id);
420       }
421     }
422   }
423 
subsetOT::fvar424   bool subset (hb_subset_context_t *c) const
425   {
426     TRACE_SUBSET (this);
427     unsigned retained_axis_count = c->plan->axes_index_map.get_population ();
428     if (!retained_axis_count) //all axes are pinned
429       return_trace (false);
430 
431     fvar *out = c->serializer->embed (this);
432     if (unlikely (!out)) return_trace (false);
433 
434     if (!c->serializer->check_assign (out->axisCount, retained_axis_count, HB_SERIALIZE_ERROR_INT_OVERFLOW))
435       return_trace (false);
436 
437     bool has_postscript_nameid = false;
438     if (instanceSize >= axisCount * 4 + 6)
439       has_postscript_nameid = true;
440 
441     if (!c->serializer->check_assign (out->instanceSize, retained_axis_count * 4 + (has_postscript_nameid ? 6 : 4),
442                                       HB_SERIALIZE_ERROR_INT_OVERFLOW))
443       return_trace (false);
444 
445     auto axes_records = get_axes ();
446     for (unsigned i = 0 ; i < (unsigned)axisCount; i++)
447     {
448       if (!c->plan->axes_index_map.has (i)) continue;
449       if (unlikely (!axes_records[i].subset (c)))
450         return_trace (false);
451     }
452 
453     if (!c->serializer->check_assign (out->firstAxis, get_size (), HB_SERIALIZE_ERROR_INT_OVERFLOW))
454       return_trace (false);
455 
456     unsigned num_retained_instances = 0;
457     for (unsigned i = 0 ; i < (unsigned)instanceCount; i++)
458     {
459       const InstanceRecord *instance = get_instance (i);
460       auto snap = c->serializer->snapshot ();
461       if (!instance->subset (c, axisCount, has_postscript_nameid))
462         c->serializer->revert (snap);
463       else
464         num_retained_instances++;
465     }
466 
467     return_trace (c->serializer->check_assign (out->instanceCount, num_retained_instances, HB_SERIALIZE_ERROR_INT_OVERFLOW));
468   }
469 
470   public:
get_axesOT::fvar471   hb_array_t<const AxisRecord> get_axes () const
472   { return hb_array (&(this+firstAxis), axisCount); }
473 
get_instanceOT::fvar474   const InstanceRecord *get_instance (unsigned int i) const
475   {
476     if (unlikely (i >= instanceCount)) return nullptr;
477    return &StructAtOffset<InstanceRecord> (&StructAfter<InstanceRecord> (get_axes ()),
478 					   i * instanceSize);
479   }
480 
481   protected:
482   FixedVersion<>version;	/* Version of the fvar table
483 				 * initially set to 0x00010000u */
484   Offset16To<AxisRecord>
485 		firstAxis;	/* Offset in bytes from the beginning of the table
486 				 * to the start of the AxisRecord array. */
487   HBUINT16	reserved;	/* This field is permanently reserved. Set to 2. */
488   HBUINT16	axisCount;	/* The number of variation axes in the font (the
489 				 * number of records in the axes array). */
490   HBUINT16	axisSize;	/* The size in bytes of each VariationAxisRecord —
491 				 * set to 20 (0x0014) for this version. */
492   HBUINT16	instanceCount;	/* The number of named instances defined in the font
493 				 * (the number of records in the instances array). */
494   HBUINT16	instanceSize;	/* The size in bytes of each InstanceRecord — set
495 				 * to either axisCount * sizeof(F16DOT16) + 4, or to
496 				 * axisCount * sizeof(F16DOT16) + 6. */
497 
498   public:
499   DEFINE_SIZE_STATIC (16);
500 };
501 
502 } /* namespace OT */
503 
504 
505 #endif /* HB_OT_VAR_FVAR_TABLE_HH */
506