1/*
2 * Copyright © 2007,2008,2009 Red Hat, Inc.
3 * Copyright © 2010,2012 Google, Inc.
4 *
5 * This is part of HarfBuzz, a text shaping library.
6 *
7 * Permission is hereby granted, without written agreement and without
8 * license or royalty fees, to use, copy, modify, and distribute this
9 * software and its documentation for any purpose, provided that the
10 * above copyright notice and the following two paragraphs appear in
11 * all copies of this software.
12 *
13 * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
14 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
15 * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
16 * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
17 * DAMAGE.
18 *
19 * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
20 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
21 * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
22 * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
23 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
24 *
25 * Red Hat Author(s): Behdad Esfahbod
26 * Google Author(s): Behdad Esfahbod
27 */
28
29#ifndef HB_OT_LAYOUT_COMMON_HH
30#define HB_OT_LAYOUT_COMMON_HH
31
32#include "hb.hh"
33#include "hb-ot-layout.hh"
34#include "hb-open-type.hh"
35#include "hb-set.hh"
36#include "hb-bimap.hh"
37
38#include "OT/Layout/Common/Coverage.hh"
39#include "OT/Layout/types.hh"
40
41// TODO(garretrieger): cleanup these after migration.
42using OT::Layout::Common::Coverage;
43using OT::Layout::Common::RangeRecord;
44using OT::Layout::SmallTypes;
45using OT::Layout::MediumTypes;
46
47
48namespace OT {
49
50template<typename Iterator>
51static inline bool ClassDef_serialize (hb_serialize_context_t *c,
52 Iterator it);
53
54static bool ClassDef_remap_and_serialize (
55 hb_serialize_context_t *c,
56 const hb_set_t &klasses,
57 bool use_class_zero,
58 hb_sorted_vector_t<hb_pair_t<hb_codepoint_t, hb_codepoint_t>> &glyph_and_klass, /* IN/OUT */
59 hb_map_t *klass_map /*IN/OUT*/);
60
61struct hb_collect_feature_substitutes_with_var_context_t
62{
63 const hb_map_t *axes_index_tag_map;
64 const hb_hashmap_t<hb_tag_t, int> *axes_location;
65 hb_hashmap_t<unsigned, hb::shared_ptr<hb_set_t>> *record_cond_idx_map;
66 hb_hashmap_t<unsigned, const Feature*> *feature_substitutes_map;
67
68 // not stored in subset_plan
69 hb_set_t *feature_indices;
70 bool apply;
71 unsigned cur_record_idx;
72 hb_hashmap_t<hb::shared_ptr<hb_map_t>, unsigned> *conditionset_map;
73};
74
75struct hb_prune_langsys_context_t
76{
77 hb_prune_langsys_context_t (const void *table_,
78 hb_hashmap_t<unsigned, hb::unique_ptr<hb_set_t>> *script_langsys_map_,
79 const hb_map_t *duplicate_feature_map_,
80 hb_set_t *new_collected_feature_indexes_)
81 :table (table_),
82 script_langsys_map (script_langsys_map_),
83 duplicate_feature_map (duplicate_feature_map_),
84 new_feature_indexes (new_collected_feature_indexes_),
85 script_count (0),langsys_feature_count (0) {}
86
87 bool visitScript ()
88 { return script_count++ < HB_MAX_SCRIPTS; }
89
90 bool visitLangsys (unsigned feature_count)
91 {
92 langsys_feature_count += feature_count;
93 return langsys_feature_count < HB_MAX_LANGSYS_FEATURE_COUNT;
94 }
95
96 public:
97 const void *table;
98 hb_hashmap_t<unsigned, hb::unique_ptr<hb_set_t>> *script_langsys_map;
99 const hb_map_t *duplicate_feature_map;
100 hb_set_t *new_feature_indexes;
101
102 private:
103 unsigned script_count;
104 unsigned langsys_feature_count;
105};
106
107struct hb_subset_layout_context_t :
108 hb_dispatch_context_t<hb_subset_layout_context_t, hb_empty_t, HB_DEBUG_SUBSET>
109{
110 const char *get_name () { return "SUBSET_LAYOUT"; }
111 static return_t default_return_value () { return hb_empty_t (); }
112
113 bool visitScript ()
114 {
115 return script_count++ < HB_MAX_SCRIPTS;
116 }
117
118 bool visitLangSys ()
119 {
120 return langsys_count++ < HB_MAX_LANGSYS;
121 }
122
123 bool visitFeatureIndex (int count)
124 {
125 feature_index_count += count;
126 return feature_index_count < HB_MAX_FEATURE_INDICES;
127 }
128
129 bool visitLookupIndex()
130 {
131 lookup_index_count++;
132 return lookup_index_count < HB_MAX_LOOKUP_VISIT_COUNT;
133 }
134
135 hb_subset_context_t *subset_context;
136 const hb_tag_t table_tag;
137 const hb_map_t *lookup_index_map;
138 const hb_hashmap_t<unsigned, hb::unique_ptr<hb_set_t>> *script_langsys_map;
139 const hb_map_t *feature_index_map;
140 const hb_hashmap_t<unsigned, const Feature*> *feature_substitutes_map;
141 hb_hashmap_t<unsigned, hb::shared_ptr<hb_set_t>> *feature_record_cond_idx_map;
142
143 unsigned cur_script_index;
144 unsigned cur_feature_var_record_idx;
145
146 hb_subset_layout_context_t (hb_subset_context_t *c_,
147 hb_tag_t tag_) :
148 subset_context (c_),
149 table_tag (tag_),
150 cur_script_index (0xFFFFu),
151 cur_feature_var_record_idx (0u),
152 script_count (0),
153 langsys_count (0),
154 feature_index_count (0),
155 lookup_index_count (0)
156 {
157 if (tag_ == HB_OT_TAG_GSUB)
158 {
159 lookup_index_map = &c_->plan->gsub_lookups;
160 script_langsys_map = &c_->plan->gsub_langsys;
161 feature_index_map = &c_->plan->gsub_features;
162 feature_substitutes_map = &c_->plan->gsub_feature_substitutes_map;
163 feature_record_cond_idx_map = c_->plan->user_axes_location.is_empty () ? nullptr : &c_->plan->gsub_feature_record_cond_idx_map;
164 }
165 else
166 {
167 lookup_index_map = &c_->plan->gpos_lookups;
168 script_langsys_map = &c_->plan->gpos_langsys;
169 feature_index_map = &c_->plan->gpos_features;
170 feature_substitutes_map = &c_->plan->gpos_feature_substitutes_map;
171 feature_record_cond_idx_map = c_->plan->user_axes_location.is_empty () ? nullptr : &c_->plan->gpos_feature_record_cond_idx_map;
172 }
173 }
174
175 private:
176 unsigned script_count;
177 unsigned langsys_count;
178 unsigned feature_index_count;
179 unsigned lookup_index_count;
180};
181
182struct VariationStore;
183struct hb_collect_variation_indices_context_t :
184 hb_dispatch_context_t<hb_collect_variation_indices_context_t>
185{
186 template <typename T>
187 return_t dispatch (const T &obj) { obj.collect_variation_indices (this); return hb_empty_t (); }
188 static return_t default_return_value () { return hb_empty_t (); }
189
190 hb_set_t *layout_variation_indices;
191 hb_hashmap_t<unsigned, hb_pair_t<unsigned, int>> *varidx_delta_map;
192 hb_vector_t<int> *normalized_coords;
193 const VariationStore *var_store;
194 const hb_set_t *glyph_set;
195 const hb_map_t *gpos_lookups;
196 float *store_cache;
197
198 hb_collect_variation_indices_context_t (hb_set_t *layout_variation_indices_,
199 hb_hashmap_t<unsigned, hb_pair_t<unsigned, int>> *varidx_delta_map_,
200 hb_vector_t<int> *normalized_coords_,
201 const VariationStore *var_store_,
202 const hb_set_t *glyph_set_,
203 const hb_map_t *gpos_lookups_,
204 float *store_cache_) :
205 layout_variation_indices (layout_variation_indices_),
206 varidx_delta_map (varidx_delta_map_),
207 normalized_coords (normalized_coords_),
208 var_store (var_store_),
209 glyph_set (glyph_set_),
210 gpos_lookups (gpos_lookups_),
211 store_cache (store_cache_) {}
212};
213
214template<typename OutputArray>
215struct subset_offset_array_t
216{
217 subset_offset_array_t (hb_subset_context_t *subset_context_,
218 OutputArray& out_,
219 const void *base_) : subset_context (subset_context_),
220 out (out_), base (base_) {}
221
222 template <typename T>
223 bool operator () (T&& offset)
224 {
225 auto snap = subset_context->serializer->snapshot ();
226 auto *o = out.serialize_append (subset_context->serializer);
227 if (unlikely (!o)) return false;
228 bool ret = o->serialize_subset (subset_context, offset, base);
229 if (!ret)
230 {
231 out.pop ();
232 subset_context->serializer->revert (snap);
233 }
234 return ret;
235 }
236
237 private:
238 hb_subset_context_t *subset_context;
239 OutputArray &out;
240 const void *base;
241};
242
243
244template<typename OutputArray, typename Arg>
245struct subset_offset_array_arg_t
246{
247 subset_offset_array_arg_t (hb_subset_context_t *subset_context_,
248 OutputArray& out_,
249 const void *base_,
250 Arg &&arg_) : subset_context (subset_context_), out (out_),
251 base (base_), arg (arg_) {}
252
253 template <typename T>
254 bool operator () (T&& offset)
255 {
256 auto snap = subset_context->serializer->snapshot ();
257 auto *o = out.serialize_append (subset_context->serializer);
258 if (unlikely (!o)) return false;
259 bool ret = o->serialize_subset (subset_context, offset, base, arg);
260 if (!ret)
261 {
262 out.pop ();
263 subset_context->serializer->revert (snap);
264 }
265 return ret;
266 }
267
268 private:
269 hb_subset_context_t *subset_context;
270 OutputArray &out;
271 const void *base;
272 Arg &&arg;
273};
274
275/*
276 * Helper to subset an array of offsets. Subsets the thing pointed to by each offset
277 * and discards the offset in the array if the subset operation results in an empty
278 * thing.
279 */
280struct
281{
282 template<typename OutputArray>
283 subset_offset_array_t<OutputArray>
284 operator () (hb_subset_context_t *subset_context, OutputArray& out,
285 const void *base) const
286 { return subset_offset_array_t<OutputArray> (subset_context, out, base); }
287
288 /* Variant with one extra argument passed to serialize_subset */
289 template<typename OutputArray, typename Arg>
290 subset_offset_array_arg_t<OutputArray, Arg>
291 operator () (hb_subset_context_t *subset_context, OutputArray& out,
292 const void *base, Arg &&arg) const
293 { return subset_offset_array_arg_t<OutputArray, Arg> (subset_context, out, base, arg); }
294}
295HB_FUNCOBJ (subset_offset_array);
296
297template<typename OutputArray>
298struct subset_record_array_t
299{
300 subset_record_array_t (hb_subset_layout_context_t *c_, OutputArray* out_,
301 const void *base_) : subset_layout_context (c_),
302 out (out_), base (base_) {}
303
304 template <typename T>
305 void
306 operator () (T&& record)
307 {
308 auto snap = subset_layout_context->subset_context->serializer->snapshot ();
309 bool ret = record.subset (subset_layout_context, base);
310 if (!ret) subset_layout_context->subset_context->serializer->revert (snap);
311 else out->len++;
312 }
313
314 private:
315 hb_subset_layout_context_t *subset_layout_context;
316 OutputArray *out;
317 const void *base;
318};
319
320template<typename OutputArray, typename Arg>
321struct subset_record_array_arg_t
322{
323 subset_record_array_arg_t (hb_subset_layout_context_t *c_, OutputArray* out_,
324 const void *base_,
325 Arg &&arg_) : subset_layout_context (c_),
326 out (out_), base (base_), arg (arg_) {}
327
328 template <typename T>
329 void
330 operator () (T&& record)
331 {
332 auto snap = subset_layout_context->subset_context->serializer->snapshot ();
333 bool ret = record.subset (subset_layout_context, base, arg);
334 if (!ret) subset_layout_context->subset_context->serializer->revert (snap);
335 else out->len++;
336 }
337
338 private:
339 hb_subset_layout_context_t *subset_layout_context;
340 OutputArray *out;
341 const void *base;
342 Arg &&arg;
343};
344
345/*
346 * Helper to subset a RecordList/record array. Subsets each Record in the array and
347 * discards the record if the subset operation returns false.
348 */
349struct
350{
351 template<typename OutputArray>
352 subset_record_array_t<OutputArray>
353 operator () (hb_subset_layout_context_t *c, OutputArray* out,
354 const void *base) const
355 { return subset_record_array_t<OutputArray> (c, out, base); }
356
357 /* Variant with one extra argument passed to subset */
358 template<typename OutputArray, typename Arg>
359 subset_record_array_arg_t<OutputArray, Arg>
360 operator () (hb_subset_layout_context_t *c, OutputArray* out,
361 const void *base, Arg &&arg) const
362 { return subset_record_array_arg_t<OutputArray, Arg> (c, out, base, arg); }
363}
364HB_FUNCOBJ (subset_record_array);
365
366
367template<typename OutputArray>
368struct serialize_math_record_array_t
369{
370 serialize_math_record_array_t (hb_serialize_context_t *serialize_context_,
371 OutputArray& out_,
372 const void *base_) : serialize_context (serialize_context_),
373 out (out_), base (base_) {}
374
375 template <typename T>
376 bool operator () (T&& record)
377 {
378 if (!serialize_context->copy (record, base)) return false;
379 out.len++;
380 return true;
381 }
382
383 private:
384 hb_serialize_context_t *serialize_context;
385 OutputArray &out;
386 const void *base;
387};
388
389/*
390 * Helper to serialize an array of MATH records.
391 */
392struct
393{
394 template<typename OutputArray>
395 serialize_math_record_array_t<OutputArray>
396 operator () (hb_serialize_context_t *serialize_context, OutputArray& out,
397 const void *base) const
398 { return serialize_math_record_array_t<OutputArray> (serialize_context, out, base); }
399
400}
401HB_FUNCOBJ (serialize_math_record_array);
402
403/*
404 *
405 * OpenType Layout Common Table Formats
406 *
407 */
408
409
410/*
411 * Script, ScriptList, LangSys, Feature, FeatureList, Lookup, LookupList
412 */
413
414struct IndexArray : Array16Of<Index>
415{
416 bool intersects (const hb_map_t *indexes) const
417 { return hb_any (*this, indexes); }
418
419 template <typename Iterator,
420 hb_requires (hb_is_iterator (Iterator))>
421 void serialize (hb_serialize_context_t *c,
422 hb_subset_layout_context_t *l,
423 Iterator it)
424 {
425 if (!it) return;
426 if (unlikely (!c->extend_min ((*this)))) return;
427
428 for (const auto _ : it)
429 {
430 if (!l->visitLookupIndex()) break;
431
432 Index i;
433 i = _;
434 c->copy (src: i);
435 this->len++;
436 }
437 }
438
439 unsigned int get_indexes (unsigned int start_offset,
440 unsigned int *_count /* IN/OUT */,
441 unsigned int *_indexes /* OUT */) const
442 {
443 if (_count)
444 {
445 + this->as_array ().sub_array (start_offset, seg_count: _count)
446 | hb_sink (hb_array (array: _indexes, length: *_count))
447 ;
448 }
449 return this->len;
450 }
451
452 void add_indexes_to (hb_set_t* output /* OUT */) const
453 {
454 output->add_array (arr: as_array ());
455 }
456};
457
458
459/* https://docs.microsoft.com/en-us/typography/opentype/spec/features_pt#size */
460struct FeatureParamsSize
461{
462 bool sanitize (hb_sanitize_context_t *c) const
463 {
464 TRACE_SANITIZE (this);
465 if (unlikely (!c->check_struct (this))) return_trace (false);
466
467 /* This subtable has some "history", if you will. Some earlier versions of
468 * Adobe tools calculated the offset of the FeatureParams subtable from the
469 * beginning of the FeatureList table! Now, that is dealt with in the
470 * Feature implementation. But we still need to be able to tell junk from
471 * real data. Note: We don't check that the nameID actually exists.
472 *
473 * Read Roberts wrote on 9/15/06 on opentype-list@indx.co.uk :
474 *
475 * Yes, it is correct that a new version of the AFDKO (version 2.0) will be
476 * coming out soon, and that the makeotf program will build a font with a
477 * 'size' feature that is correct by the specification.
478 *
479 * The specification for this feature tag is in the "OpenType Layout Tag
480 * Registry". You can see a copy of this at:
481 * https://docs.microsoft.com/en-us/typography/opentype/spec/features_pt#tag-size
482 *
483 * Here is one set of rules to determine if the 'size' feature is built
484 * correctly, or as by the older versions of MakeOTF. You may be able to do
485 * better.
486 *
487 * Assume that the offset to the size feature is according to specification,
488 * and make the following value checks. If it fails, assume the size
489 * feature is calculated as versions of MakeOTF before the AFDKO 2.0 built it.
490 * If this fails, reject the 'size' feature. The older makeOTF's calculated the
491 * offset from the beginning of the FeatureList table, rather than from the
492 * beginning of the 'size' Feature table.
493 *
494 * If "design size" == 0:
495 * fails check
496 *
497 * Else if ("subfamily identifier" == 0 and
498 * "range start" == 0 and
499 * "range end" == 0 and
500 * "range start" == 0 and
501 * "menu name ID" == 0)
502 * passes check: this is the format used when there is a design size
503 * specified, but there is no recommended size range.
504 *
505 * Else if ("design size" < "range start" or
506 * "design size" > "range end" or
507 * "range end" <= "range start" or
508 * "menu name ID" < 256 or
509 * "menu name ID" > 32767 or
510 * menu name ID is not a name ID which is actually in the name table)
511 * fails test
512 * Else
513 * passes test.
514 */
515
516 if (!designSize)
517 return_trace (false);
518 else if (subfamilyID == 0 &&
519 subfamilyNameID == 0 &&
520 rangeStart == 0 &&
521 rangeEnd == 0)
522 return_trace (true);
523 else if (designSize < rangeStart ||
524 designSize > rangeEnd ||
525 subfamilyNameID < 256 ||
526 subfamilyNameID > 32767)
527 return_trace (false);
528 else
529 return_trace (true);
530 }
531
532 void collect_name_ids (hb_set_t *nameids_to_retain /* OUT */) const
533 { nameids_to_retain->add (g: subfamilyNameID); }
534
535 bool subset (hb_subset_context_t *c) const
536 {
537 TRACE_SUBSET (this);
538 return_trace ((bool) c->serializer->embed (*this));
539 }
540
541 HBUINT16 designSize; /* Represents the design size in 720/inch
542 * units (decipoints). The design size entry
543 * must be non-zero. When there is a design
544 * size but no recommended size range, the
545 * rest of the array will consist of zeros. */
546 HBUINT16 subfamilyID; /* Has no independent meaning, but serves
547 * as an identifier that associates fonts
548 * in a subfamily. All fonts which share a
549 * Preferred or Font Family name and which
550 * differ only by size range shall have the
551 * same subfamily value, and no fonts which
552 * differ in weight or style shall have the
553 * same subfamily value. If this value is
554 * zero, the remaining fields in the array
555 * will be ignored. */
556 NameID subfamilyNameID;/* If the preceding value is non-zero, this
557 * value must be set in the range 256 - 32767
558 * (inclusive). It records the value of a
559 * field in the name table, which must
560 * contain English-language strings encoded
561 * in Windows Unicode and Macintosh Roman,
562 * and may contain additional strings
563 * localized to other scripts and languages.
564 * Each of these strings is the name an
565 * application should use, in combination
566 * with the family name, to represent the
567 * subfamily in a menu. Applications will
568 * choose the appropriate version based on
569 * their selection criteria. */
570 HBUINT16 rangeStart; /* Large end of the recommended usage range
571 * (inclusive), stored in 720/inch units
572 * (decipoints). */
573 HBUINT16 rangeEnd; /* Small end of the recommended usage range
574 (exclusive), stored in 720/inch units
575 * (decipoints). */
576 public:
577 DEFINE_SIZE_STATIC (10);
578};
579
580/* https://docs.microsoft.com/en-us/typography/opentype/spec/features_pt#ssxx */
581struct FeatureParamsStylisticSet
582{
583 bool sanitize (hb_sanitize_context_t *c) const
584 {
585 TRACE_SANITIZE (this);
586 /* Right now minorVersion is at zero. Which means, any table supports
587 * the uiNameID field. */
588 return_trace (c->check_struct (this));
589 }
590
591 void collect_name_ids (hb_set_t *nameids_to_retain /* OUT */) const
592 { nameids_to_retain->add (g: uiNameID); }
593
594 bool subset (hb_subset_context_t *c) const
595 {
596 TRACE_SUBSET (this);
597 return_trace ((bool) c->serializer->embed (*this));
598 }
599
600 HBUINT16 version; /* (set to 0): This corresponds to a “minor”
601 * version number. Additional data may be
602 * added to the end of this Feature Parameters
603 * table in the future. */
604
605 NameID uiNameID; /* The 'name' table name ID that specifies a
606 * string (or strings, for multiple languages)
607 * for a user-interface label for this
608 * feature. The values of uiLabelNameId and
609 * sampleTextNameId are expected to be in the
610 * font-specific name ID range (256-32767),
611 * though that is not a requirement in this
612 * Feature Parameters specification. The
613 * user-interface label for the feature can
614 * be provided in multiple languages. An
615 * English string should be included as a
616 * fallback. The string should be kept to a
617 * minimal length to fit comfortably with
618 * different application interfaces. */
619 public:
620 DEFINE_SIZE_STATIC (4);
621};
622
623/* https://docs.microsoft.com/en-us/typography/opentype/spec/features_ae#cv01-cv99 */
624struct FeatureParamsCharacterVariants
625{
626 unsigned
627 get_characters (unsigned start_offset, unsigned *char_count, hb_codepoint_t *chars) const
628 {
629 if (char_count)
630 {
631 + characters.as_array ().sub_array (start_offset, seg_count: char_count)
632 | hb_sink (hb_array (array: chars, length: *char_count))
633 ;
634 }
635 return characters.len;
636 }
637
638 unsigned get_size () const
639 { return min_size + characters.len * HBUINT24::static_size; }
640
641 void collect_name_ids (hb_set_t *nameids_to_retain /* OUT */) const
642 {
643 if (featUILableNameID) nameids_to_retain->add (g: featUILableNameID);
644 if (featUITooltipTextNameID) nameids_to_retain->add (g: featUITooltipTextNameID);
645 if (sampleTextNameID) nameids_to_retain->add (g: sampleTextNameID);
646
647 if (!firstParamUILabelNameID || !numNamedParameters || numNamedParameters >= 0x7FFF)
648 return;
649
650 unsigned last_name_id = (unsigned) firstParamUILabelNameID + (unsigned) numNamedParameters - 1;
651 if (last_name_id >= 256 && last_name_id <= 32767)
652 nameids_to_retain->add_range (a: firstParamUILabelNameID, b: last_name_id);
653 }
654
655 bool subset (hb_subset_context_t *c) const
656 {
657 TRACE_SUBSET (this);
658 return_trace ((bool) c->serializer->embed (*this));
659 }
660
661 bool sanitize (hb_sanitize_context_t *c) const
662 {
663 TRACE_SANITIZE (this);
664 return_trace (c->check_struct (this) &&
665 characters.sanitize (c));
666 }
667
668 HBUINT16 format; /* Format number is set to 0. */
669 NameID featUILableNameID; /* The ‘name’ table name ID that
670 * specifies a string (or strings,
671 * for multiple languages) for a
672 * user-interface label for this
673 * feature. (May be NULL.) */
674 NameID featUITooltipTextNameID;/* The ‘name’ table name ID that
675 * specifies a string (or strings,
676 * for multiple languages) that an
677 * application can use for tooltip
678 * text for this feature. (May be
679 * nullptr.) */
680 NameID sampleTextNameID; /* The ‘name’ table name ID that
681 * specifies sample text that
682 * illustrates the effect of this
683 * feature. (May be NULL.) */
684 HBUINT16 numNamedParameters; /* Number of named parameters. (May
685 * be zero.) */
686 NameID firstParamUILabelNameID;/* The first ‘name’ table name ID
687 * used to specify strings for
688 * user-interface labels for the
689 * feature parameters. (Must be zero
690 * if numParameters is zero.) */
691 Array16Of<HBUINT24>
692 characters; /* Array of the Unicode Scalar Value
693 * of the characters for which this
694 * feature provides glyph variants.
695 * (May be zero.) */
696 public:
697 DEFINE_SIZE_ARRAY (14, characters);
698};
699
700struct FeatureParams
701{
702 bool sanitize (hb_sanitize_context_t *c, hb_tag_t tag) const
703 {
704#ifdef HB_NO_LAYOUT_FEATURE_PARAMS
705 return true;
706#endif
707 TRACE_SANITIZE (this);
708 if (tag == HB_TAG ('s','i','z','e'))
709 return_trace (u.size.sanitize (c));
710 if ((tag & 0xFFFF0000u) == HB_TAG ('s','s','\0','\0')) /* ssXX */
711 return_trace (u.stylisticSet.sanitize (c));
712 if ((tag & 0xFFFF0000u) == HB_TAG ('c','v','\0','\0')) /* cvXX */
713 return_trace (u.characterVariants.sanitize (c));
714 return_trace (true);
715 }
716
717 void collect_name_ids (hb_tag_t tag, hb_set_t *nameids_to_retain /* OUT */) const
718 {
719#ifdef HB_NO_LAYOUT_FEATURE_PARAMS
720 return;
721#endif
722 if (tag == HB_TAG ('s','i','z','e'))
723 return (u.size.collect_name_ids (nameids_to_retain));
724 if ((tag & 0xFFFF0000u) == HB_TAG ('s','s','\0','\0')) /* ssXX */
725 return (u.stylisticSet.collect_name_ids (nameids_to_retain));
726 if ((tag & 0xFFFF0000u) == HB_TAG ('c','v','\0','\0')) /* cvXX */
727 return (u.characterVariants.collect_name_ids (nameids_to_retain));
728 }
729
730 bool subset (hb_subset_context_t *c, const Tag* tag) const
731 {
732 TRACE_SUBSET (this);
733 if (!tag) return_trace (false);
734 if (*tag == HB_TAG ('s','i','z','e'))
735 return_trace (u.size.subset (c));
736 if ((*tag & 0xFFFF0000u) == HB_TAG ('s','s','\0','\0')) /* ssXX */
737 return_trace (u.stylisticSet.subset (c));
738 if ((*tag & 0xFFFF0000u) == HB_TAG ('c','v','\0','\0')) /* cvXX */
739 return_trace (u.characterVariants.subset (c));
740 return_trace (false);
741 }
742
743#ifndef HB_NO_LAYOUT_FEATURE_PARAMS
744 const FeatureParamsSize& get_size_params (hb_tag_t tag) const
745 {
746 if (tag == HB_TAG ('s','i','z','e'))
747 return u.size;
748 return Null (FeatureParamsSize);
749 }
750 const FeatureParamsStylisticSet& get_stylistic_set_params (hb_tag_t tag) const
751 {
752 if ((tag & 0xFFFF0000u) == HB_TAG ('s','s','\0','\0')) /* ssXX */
753 return u.stylisticSet;
754 return Null (FeatureParamsStylisticSet);
755 }
756 const FeatureParamsCharacterVariants& get_character_variants_params (hb_tag_t tag) const
757 {
758 if ((tag & 0xFFFF0000u) == HB_TAG ('c','v','\0','\0')) /* cvXX */
759 return u.characterVariants;
760 return Null (FeatureParamsCharacterVariants);
761 }
762#endif
763
764 private:
765 union {
766 FeatureParamsSize size;
767 FeatureParamsStylisticSet stylisticSet;
768 FeatureParamsCharacterVariants characterVariants;
769 } u;
770 public:
771 DEFINE_SIZE_MIN (0);
772};
773
774struct Record_sanitize_closure_t {
775 hb_tag_t tag;
776 const void *list_base;
777};
778
779struct Feature
780{
781 unsigned int get_lookup_count () const
782 { return lookupIndex.len; }
783 hb_tag_t get_lookup_index (unsigned int i) const
784 { return lookupIndex[i]; }
785 unsigned int get_lookup_indexes (unsigned int start_index,
786 unsigned int *lookup_count /* IN/OUT */,
787 unsigned int *lookup_tags /* OUT */) const
788 { return lookupIndex.get_indexes (start_offset: start_index, count: lookup_count, indexes: lookup_tags); }
789 void add_lookup_indexes_to (hb_set_t *lookup_indexes) const
790 { lookupIndex.add_indexes_to (output: lookup_indexes); }
791
792 const FeatureParams &get_feature_params () const
793 { return this+featureParams; }
794
795 bool intersects_lookup_indexes (const hb_map_t *lookup_indexes) const
796 { return lookupIndex.intersects (indexes: lookup_indexes); }
797
798 void collect_name_ids (hb_tag_t tag, hb_set_t *nameids_to_retain /* OUT */) const
799 {
800 if (featureParams)
801 get_feature_params ().collect_name_ids (tag, nameids_to_retain);
802 }
803
804 bool subset (hb_subset_context_t *c,
805 hb_subset_layout_context_t *l,
806 const Tag *tag = nullptr) const
807 {
808 TRACE_SUBSET (this);
809 auto *out = c->serializer->start_embed (obj: *this);
810 if (unlikely (!out || !c->serializer->extend_min (out))) return_trace (false);
811
812 out->featureParams.serialize_subset (c, src: featureParams, src_base: this, ds&: tag);
813
814 auto it =
815 + hb_iter (lookupIndex)
816 | hb_filter (l->lookup_index_map)
817 | hb_map (l->lookup_index_map)
818 ;
819
820 out->lookupIndex.serialize (c: c->serializer, l, it);
821 // The decision to keep or drop this feature is already made before we get here
822 // so always retain it.
823 return_trace (true);
824 }
825
826 bool sanitize (hb_sanitize_context_t *c,
827 const Record_sanitize_closure_t *closure = nullptr) const
828 {
829 TRACE_SANITIZE (this);
830 if (unlikely (!(c->check_struct (this) && lookupIndex.sanitize (c))))
831 return_trace (false);
832
833 /* Some earlier versions of Adobe tools calculated the offset of the
834 * FeatureParams subtable from the beginning of the FeatureList table!
835 *
836 * If sanitizing "failed" for the FeatureParams subtable, try it with the
837 * alternative location. We would know sanitize "failed" if old value
838 * of the offset was non-zero, but it's zeroed now.
839 *
840 * Only do this for the 'size' feature, since at the time of the faulty
841 * Adobe tools, only the 'size' feature had FeatureParams defined.
842 */
843
844 if (likely (featureParams.is_null ()))
845 return_trace (true);
846
847 unsigned int orig_offset = featureParams;
848 if (unlikely (!featureParams.sanitize (c, this, closure ? closure->tag : HB_TAG_NONE)))
849 return_trace (false);
850
851 if (featureParams == 0 && closure &&
852 closure->tag == HB_TAG ('s','i','z','e') &&
853 closure->list_base && closure->list_base < this)
854 {
855 unsigned int new_offset_int = orig_offset -
856 (((char *) this) - ((char *) closure->list_base));
857
858 Offset16To<FeatureParams> new_offset;
859 /* Check that it would not overflow. */
860 new_offset = new_offset_int;
861 if (new_offset == new_offset_int &&
862 c->try_set (obj: &featureParams, v: new_offset_int) &&
863 !featureParams.sanitize (c, base: this, ds: closure ? closure->tag : HB_TAG_NONE))
864 return_trace (false);
865 }
866
867 return_trace (true);
868 }
869
870 Offset16To<FeatureParams>
871 featureParams; /* Offset to Feature Parameters table (if one
872 * has been defined for the feature), relative
873 * to the beginning of the Feature Table; = Null
874 * if not required */
875 IndexArray lookupIndex; /* Array of LookupList indices */
876 public:
877 DEFINE_SIZE_ARRAY_SIZED (4, lookupIndex);
878};
879
880template <typename Type>
881struct Record
882{
883 int cmp (hb_tag_t a) const { return tag.cmp (a); }
884
885 bool subset (hb_subset_layout_context_t *c, const void *base, const void *f_sub = nullptr) const
886 {
887 TRACE_SUBSET (this);
888 auto *out = c->subset_context->serializer->embed (this);
889 if (unlikely (!out)) return_trace (false);
890
891 if (!f_sub)
892 return_trace (out->offset.serialize_subset (c->subset_context, offset, base, c, &tag));
893
894 const Feature& f = *reinterpret_cast<const Feature *> (f_sub);
895 auto *s = c->subset_context->serializer;
896 s->push ();
897
898 out->offset = 0;
899 bool ret = f.subset (c: c->subset_context, l: c, tag: &tag);
900 if (ret)
901 s->add_link (out->offset, s->pop_pack ());
902 else
903 s->pop_discard ();
904
905 return_trace (ret);
906 }
907
908 bool sanitize (hb_sanitize_context_t *c, const void *base) const
909 {
910 TRACE_SANITIZE (this);
911 const Record_sanitize_closure_t closure = {.tag: tag, .list_base: base};
912 return_trace (c->check_struct (this) && offset.sanitize (c, base, &closure));
913 }
914
915 Tag tag; /* 4-byte Tag identifier */
916 Offset16To<Type>
917 offset; /* Offset from beginning of object holding
918 * the Record */
919 public:
920 DEFINE_SIZE_STATIC (6);
921};
922
923template <typename Type>
924struct RecordArrayOf : SortedArray16Of<Record<Type>>
925{
926 const Offset16To<Type>& get_offset (unsigned int i) const
927 { return (*this)[i].offset; }
928 Offset16To<Type>& get_offset (unsigned int i)
929 { return (*this)[i].offset; }
930 const Tag& get_tag (unsigned int i) const
931 { return (*this)[i].tag; }
932 unsigned int get_tags (unsigned int start_offset,
933 unsigned int *record_count /* IN/OUT */,
934 hb_tag_t *record_tags /* OUT */) const
935 {
936 if (record_count)
937 {
938 + this->as_array ().sub_array (start_offset, record_count)
939 | hb_map (&Record<Type>::tag)
940 | hb_sink (hb_array (array: record_tags, length: *record_count))
941 ;
942 }
943 return this->len;
944 }
945 bool find_index (hb_tag_t tag, unsigned int *index) const
946 {
947 return this->bfind (tag, index, HB_NOT_FOUND_STORE, Index::NOT_FOUND_INDEX);
948 }
949};
950
951template <typename Type>
952struct RecordListOf : RecordArrayOf<Type>
953{
954 const Type& operator [] (unsigned int i) const
955 { return this+this->get_offset (i); }
956
957 bool subset (hb_subset_context_t *c,
958 hb_subset_layout_context_t *l) const
959 {
960 TRACE_SUBSET (this);
961 auto *out = c->serializer->start_embed (*this);
962 if (unlikely (!c->serializer->extend_min (out))) return_trace (false);
963
964 + this->iter ()
965 | hb_apply (subset_record_array (l, out, this))
966 ;
967 return_trace (true);
968 }
969
970 bool sanitize (hb_sanitize_context_t *c) const
971 {
972 TRACE_SANITIZE (this);
973 return_trace (RecordArrayOf<Type>::sanitize (c, this));
974 }
975};
976
977struct RecordListOfFeature : RecordListOf<Feature>
978{
979 bool subset (hb_subset_context_t *c,
980 hb_subset_layout_context_t *l) const
981 {
982 TRACE_SUBSET (this);
983 auto *out = c->serializer->start_embed (obj: *this);
984 if (unlikely (!out || !c->serializer->extend_min (out))) return_trace (false);
985
986 + hb_enumerate (*this)
987 | hb_filter (l->feature_index_map, hb_first)
988 | hb_apply ([l, out, this] (const hb_pair_t<unsigned, const Record<Feature>&>& _)
989 {
990 const Feature *f_sub = nullptr;
991 const Feature **f = nullptr;
992 if (l->feature_substitutes_map->has (key: _.first, vp: &f))
993 f_sub = *f;
994
995 subset_record_array (l, out, this, f_sub) (_.second);
996 })
997 ;
998
999 return_trace (true);
1000 }
1001};
1002
1003typedef RecordListOf<Feature> FeatureList;
1004
1005
1006struct LangSys
1007{
1008 unsigned int get_feature_count () const
1009 { return featureIndex.len; }
1010 hb_tag_t get_feature_index (unsigned int i) const
1011 { return featureIndex[i]; }
1012 unsigned int get_feature_indexes (unsigned int start_offset,
1013 unsigned int *feature_count /* IN/OUT */,
1014 unsigned int *feature_indexes /* OUT */) const
1015 { return featureIndex.get_indexes (start_offset, count: feature_count, indexes: feature_indexes); }
1016 void add_feature_indexes_to (hb_set_t *feature_indexes) const
1017 { featureIndex.add_indexes_to (output: feature_indexes); }
1018
1019 bool has_required_feature () const { return reqFeatureIndex != 0xFFFFu; }
1020 unsigned int get_required_feature_index () const
1021 {
1022 if (reqFeatureIndex == 0xFFFFu)
1023 return Index::NOT_FOUND_INDEX;
1024 return reqFeatureIndex;
1025 }
1026
1027 LangSys* copy (hb_serialize_context_t *c) const
1028 {
1029 TRACE_SERIALIZE (this);
1030 return_trace (c->embed (*this));
1031 }
1032
1033 bool compare (const LangSys& o, const hb_map_t *feature_index_map) const
1034 {
1035 if (reqFeatureIndex != o.reqFeatureIndex)
1036 return false;
1037
1038 auto iter =
1039 + hb_iter (featureIndex)
1040 | hb_filter (feature_index_map)
1041 | hb_map (feature_index_map)
1042 ;
1043
1044 auto o_iter =
1045 + hb_iter (o.featureIndex)
1046 | hb_filter (feature_index_map)
1047 | hb_map (feature_index_map)
1048 ;
1049
1050 for (; iter && o_iter; iter++, o_iter++)
1051 {
1052 unsigned a = *iter;
1053 unsigned b = *o_iter;
1054 if (a != b) return false;
1055 }
1056
1057 if (iter || o_iter) return false;
1058
1059 return true;
1060 }
1061
1062 void collect_features (hb_prune_langsys_context_t *c) const
1063 {
1064 if (!has_required_feature () && !get_feature_count ()) return;
1065 if (has_required_feature () &&
1066 c->duplicate_feature_map->has (key: reqFeatureIndex))
1067 c->new_feature_indexes->add (g: get_required_feature_index ());
1068
1069 + hb_iter (featureIndex)
1070 | hb_filter (c->duplicate_feature_map)
1071 | hb_sink (c->new_feature_indexes)
1072 ;
1073 }
1074
1075 bool subset (hb_subset_context_t *c,
1076 hb_subset_layout_context_t *l,
1077 const Tag *tag = nullptr) const
1078 {
1079 TRACE_SUBSET (this);
1080 auto *out = c->serializer->start_embed (obj: *this);
1081 if (unlikely (!out || !c->serializer->extend_min (out))) return_trace (false);
1082
1083 const uint32_t *v;
1084 out->reqFeatureIndex = l->feature_index_map->has (key: reqFeatureIndex, vp: &v) ? *v : 0xFFFFu;
1085
1086 if (!l->visitFeatureIndex (count: featureIndex.len))
1087 return_trace (false);
1088
1089 auto it =
1090 + hb_iter (featureIndex)
1091 | hb_filter (l->feature_index_map)
1092 | hb_map (l->feature_index_map)
1093 ;
1094
1095 bool ret = bool (it);
1096 out->featureIndex.serialize (c: c->serializer, l, it);
1097 return_trace (ret);
1098 }
1099
1100 bool sanitize (hb_sanitize_context_t *c,
1101 const Record_sanitize_closure_t * = nullptr) const
1102 {
1103 TRACE_SANITIZE (this);
1104 return_trace (c->check_struct (this) && featureIndex.sanitize (c));
1105 }
1106
1107 Offset16 lookupOrderZ; /* = Null (reserved for an offset to a
1108 * reordering table) */
1109 HBUINT16 reqFeatureIndex;/* Index of a feature required for this
1110 * language system--if no required features
1111 * = 0xFFFFu */
1112 IndexArray featureIndex; /* Array of indices into the FeatureList */
1113 public:
1114 DEFINE_SIZE_ARRAY_SIZED (6, featureIndex);
1115};
1116DECLARE_NULL_NAMESPACE_BYTES (OT, LangSys);
1117
1118struct Script
1119{
1120 unsigned int get_lang_sys_count () const
1121 { return langSys.len; }
1122 const Tag& get_lang_sys_tag (unsigned int i) const
1123 { return langSys.get_tag (i); }
1124 unsigned int get_lang_sys_tags (unsigned int start_offset,
1125 unsigned int *lang_sys_count /* IN/OUT */,
1126 hb_tag_t *lang_sys_tags /* OUT */) const
1127 { return langSys.get_tags (start_offset, record_count: lang_sys_count, record_tags: lang_sys_tags); }
1128 const LangSys& get_lang_sys (unsigned int i) const
1129 {
1130 if (i == Index::NOT_FOUND_INDEX) return get_default_lang_sys ();
1131 return this+langSys[i].offset;
1132 }
1133 bool find_lang_sys_index (hb_tag_t tag, unsigned int *index) const
1134 { return langSys.find_index (tag, index); }
1135
1136 bool has_default_lang_sys () const { return defaultLangSys != 0; }
1137 const LangSys& get_default_lang_sys () const { return this+defaultLangSys; }
1138
1139 void prune_langsys (hb_prune_langsys_context_t *c,
1140 unsigned script_index) const
1141 {
1142 if (!has_default_lang_sys () && !get_lang_sys_count ()) return;
1143 if (!c->visitScript ()) return;
1144
1145 if (!c->script_langsys_map->has (key: script_index))
1146 {
1147 if (unlikely (!c->script_langsys_map->set (script_index, hb::unique_ptr<hb_set_t> {hb_set_create ()})))
1148 return;
1149 }
1150
1151 if (has_default_lang_sys ())
1152 {
1153 //only collect features from non-redundant langsys
1154 const LangSys& d = get_default_lang_sys ();
1155 if (c->visitLangsys (feature_count: d.get_feature_count ())) {
1156 d.collect_features (c);
1157 }
1158
1159 for (auto _ : + hb_enumerate (langSys))
1160 {
1161 const LangSys& l = this+_.second.offset;
1162 if (!c->visitLangsys (feature_count: l.get_feature_count ())) continue;
1163 if (l.compare (o: d, feature_index_map: c->duplicate_feature_map)) continue;
1164
1165 l.collect_features (c);
1166 c->script_langsys_map->get (key: script_index)->add (g: _.first);
1167 }
1168 }
1169 else
1170 {
1171 for (auto _ : + hb_enumerate (langSys))
1172 {
1173 const LangSys& l = this+_.second.offset;
1174 if (!c->visitLangsys (feature_count: l.get_feature_count ())) continue;
1175 l.collect_features (c);
1176 c->script_langsys_map->get (key: script_index)->add (g: _.first);
1177 }
1178 }
1179 }
1180
1181 bool subset (hb_subset_context_t *c,
1182 hb_subset_layout_context_t *l,
1183 const Tag *tag) const
1184 {
1185 TRACE_SUBSET (this);
1186 if (!l->visitScript ()) return_trace (false);
1187 if (tag && !c->plan->layout_scripts.has (k: *tag))
1188 return false;
1189
1190 auto *out = c->serializer->start_embed (obj: *this);
1191 if (unlikely (!out || !c->serializer->extend_min (out))) return_trace (false);
1192
1193 bool defaultLang = false;
1194 if (has_default_lang_sys ())
1195 {
1196 c->serializer->push ();
1197 const LangSys& ls = this+defaultLangSys;
1198 bool ret = ls.subset (c, l);
1199 if (!ret && tag && *tag != HB_TAG ('D', 'F', 'L', 'T'))
1200 {
1201 c->serializer->pop_discard ();
1202 out->defaultLangSys = 0;
1203 }
1204 else
1205 {
1206 c->serializer->add_link (ofs&: out->defaultLangSys, objidx: c->serializer->pop_pack ());
1207 defaultLang = true;
1208 }
1209 }
1210
1211 const hb_set_t *active_langsys = l->script_langsys_map->get (key: l->cur_script_index);
1212 if (active_langsys)
1213 {
1214 + hb_enumerate (langSys)
1215 | hb_filter (active_langsys, hb_first)
1216 | hb_map (hb_second)
1217 | hb_filter ([=] (const Record<LangSys>& record) {return l->visitLangSys (); })
1218 | hb_apply (subset_record_array (l, &(out->langSys), this))
1219 ;
1220 }
1221
1222 return_trace (bool (out->langSys.len) || defaultLang || l->table_tag == HB_OT_TAG_GSUB);
1223 }
1224
1225 bool sanitize (hb_sanitize_context_t *c,
1226 const Record_sanitize_closure_t * = nullptr) const
1227 {
1228 TRACE_SANITIZE (this);
1229 return_trace (defaultLangSys.sanitize (c, this) && langSys.sanitize (c, this));
1230 }
1231
1232 protected:
1233 Offset16To<LangSys>
1234 defaultLangSys; /* Offset to DefaultLangSys table--from
1235 * beginning of Script table--may be Null */
1236 RecordArrayOf<LangSys>
1237 langSys; /* Array of LangSysRecords--listed
1238 * alphabetically by LangSysTag */
1239 public:
1240 DEFINE_SIZE_ARRAY_SIZED (4, langSys);
1241};
1242
1243struct RecordListOfScript : RecordListOf<Script>
1244{
1245 bool subset (hb_subset_context_t *c,
1246 hb_subset_layout_context_t *l) const
1247 {
1248 TRACE_SUBSET (this);
1249 auto *out = c->serializer->start_embed (obj: *this);
1250 if (unlikely (!out || !c->serializer->extend_min (out))) return_trace (false);
1251
1252 for (auto _ : + hb_enumerate (*this))
1253 {
1254 auto snap = c->serializer->snapshot ();
1255 l->cur_script_index = _.first;
1256 bool ret = _.second.subset (c: l, base: this);
1257 if (!ret) c->serializer->revert (snap);
1258 else out->len++;
1259 }
1260
1261 return_trace (true);
1262 }
1263};
1264
1265typedef RecordListOfScript ScriptList;
1266
1267
1268
1269struct LookupFlag : HBUINT16
1270{
1271 enum Flags {
1272 RightToLeft = 0x0001u,
1273 IgnoreBaseGlyphs = 0x0002u,
1274 IgnoreLigatures = 0x0004u,
1275 IgnoreMarks = 0x0008u,
1276 IgnoreFlags = 0x000Eu,
1277 UseMarkFilteringSet = 0x0010u,
1278 Reserved = 0x00E0u,
1279 MarkAttachmentType = 0xFF00u
1280 };
1281 public:
1282 DEFINE_SIZE_STATIC (2);
1283};
1284
1285} /* namespace OT */
1286/* This has to be outside the namespace. */
1287HB_MARK_AS_FLAG_T (OT::LookupFlag::Flags);
1288namespace OT {
1289
1290struct Lookup
1291{
1292 unsigned int get_subtable_count () const { return subTable.len; }
1293
1294 template <typename TSubTable>
1295 const Array16OfOffset16To<TSubTable>& get_subtables () const
1296 { return reinterpret_cast<const Array16OfOffset16To<TSubTable> &> (subTable); }
1297 template <typename TSubTable>
1298 Array16OfOffset16To<TSubTable>& get_subtables ()
1299 { return reinterpret_cast<Array16OfOffset16To<TSubTable> &> (subTable); }
1300
1301 template <typename TSubTable>
1302 const TSubTable& get_subtable (unsigned int i) const
1303 { return this+get_subtables<TSubTable> ()[i]; }
1304 template <typename TSubTable>
1305 TSubTable& get_subtable (unsigned int i)
1306 { return this+get_subtables<TSubTable> ()[i]; }
1307
1308 unsigned int get_size () const
1309 {
1310 const HBUINT16 &markFilteringSet = StructAfter<const HBUINT16> (X: subTable);
1311 if (lookupFlag & LookupFlag::UseMarkFilteringSet)
1312 return (const char *) &StructAfter<const char> (X: markFilteringSet) - (const char *) this;
1313 return (const char *) &markFilteringSet - (const char *) this;
1314 }
1315
1316 unsigned int get_type () const { return lookupType; }
1317
1318 /* lookup_props is a 32-bit integer where the lower 16-bit is LookupFlag and
1319 * higher 16-bit is mark-filtering-set if the lookup uses one.
1320 * Not to be confused with glyph_props which is very similar. */
1321 uint32_t get_props () const
1322 {
1323 unsigned int flag = lookupFlag;
1324 if (unlikely (flag & LookupFlag::UseMarkFilteringSet))
1325 {
1326 const HBUINT16 &markFilteringSet = StructAfter<HBUINT16> (X: subTable);
1327 flag += (markFilteringSet << 16);
1328 }
1329 return flag;
1330 }
1331
1332 template <typename TSubTable, typename context_t, typename ...Ts>
1333 typename context_t::return_t dispatch (context_t *c, Ts&&... ds) const
1334 {
1335 unsigned int lookup_type = get_type ();
1336 TRACE_DISPATCH (this, lookup_type);
1337 unsigned int count = get_subtable_count ();
1338 for (unsigned int i = 0; i < count; i++) {
1339 typename context_t::return_t r = get_subtable<TSubTable> (i).dispatch (c, lookup_type, std::forward<Ts> (ds)...);
1340 if (c->stop_sublookup_iteration (r))
1341 return_trace (r);
1342 }
1343 return_trace (c->default_return_value ());
1344 }
1345
1346 bool serialize (hb_serialize_context_t *c,
1347 unsigned int lookup_type,
1348 uint32_t lookup_props,
1349 unsigned int num_subtables)
1350 {
1351 TRACE_SERIALIZE (this);
1352 if (unlikely (!c->extend_min (this))) return_trace (false);
1353 lookupType = lookup_type;
1354 lookupFlag = lookup_props & 0xFFFFu;
1355 if (unlikely (!subTable.serialize (c, num_subtables))) return_trace (false);
1356 if (lookupFlag & LookupFlag::UseMarkFilteringSet)
1357 {
1358 if (unlikely (!c->extend (this))) return_trace (false);
1359 HBUINT16 &markFilteringSet = StructAfter<HBUINT16> (X&: subTable);
1360 markFilteringSet = lookup_props >> 16;
1361 }
1362 return_trace (true);
1363 }
1364
1365 template <typename TSubTable>
1366 bool subset (hb_subset_context_t *c) const
1367 {
1368 TRACE_SUBSET (this);
1369 auto *out = c->serializer->start_embed (obj: *this);
1370 if (unlikely (!out || !c->serializer->extend_min (out))) return_trace (false);
1371 out->lookupType = lookupType;
1372 out->lookupFlag = lookupFlag;
1373
1374 const hb_set_t *glyphset = c->plan->glyphset_gsub ();
1375 unsigned int lookup_type = get_type ();
1376 + hb_iter (get_subtables <TSubTable> ())
1377 | hb_filter ([this, glyphset, lookup_type] (const Offset16To<TSubTable> &_) { return (this+_).intersects (glyphset, lookup_type); })
1378 | hb_apply (subset_offset_array (c, out->get_subtables<TSubTable> (), this, lookup_type))
1379 ;
1380
1381 if (lookupFlag & LookupFlag::UseMarkFilteringSet)
1382 {
1383 if (unlikely (!c->serializer->extend (out))) return_trace (false);
1384 const HBUINT16 &markFilteringSet = StructAfter<HBUINT16> (X: subTable);
1385 HBUINT16 &outMarkFilteringSet = StructAfter<HBUINT16> (X&: out->subTable);
1386 outMarkFilteringSet = markFilteringSet;
1387 }
1388
1389 // Always keep the lookup even if it's empty. The rest of layout subsetting depends on lookup
1390 // indices being consistent with those computed during planning. So if an empty lookup is
1391 // discarded during the subset phase it will invalidate all subsequent lookup indices.
1392 // Generally we shouldn't end up with an empty lookup as we pre-prune them during the planning
1393 // phase, but it can happen in rare cases such as when during closure subtable is considered
1394 // degenerate (see: https://github.com/harfbuzz/harfbuzz/issues/3853)
1395 return_trace (true);
1396 }
1397
1398 template <typename TSubTable>
1399 bool sanitize (hb_sanitize_context_t *c) const
1400 {
1401 TRACE_SANITIZE (this);
1402 if (!(c->check_struct (obj: this) && subTable.sanitize (c))) return_trace (false);
1403
1404 unsigned subtables = get_subtable_count ();
1405 if (unlikely (!c->visit_subtables (subtables))) return_trace (false);
1406
1407 if (lookupFlag & LookupFlag::UseMarkFilteringSet)
1408 {
1409 const HBUINT16 &markFilteringSet = StructAfter<HBUINT16> (X: subTable);
1410 if (!markFilteringSet.sanitize (c)) return_trace (false);
1411 }
1412
1413 if (unlikely (!get_subtables<TSubTable> ().sanitize (c, this, get_type ())))
1414 return_trace (false);
1415
1416 if (unlikely (get_type () == TSubTable::Extension && !c->get_edit_count ()))
1417 {
1418 /* The spec says all subtables of an Extension lookup should
1419 * have the same type, which shall not be the Extension type
1420 * itself (but we already checked for that).
1421 * This is specially important if one has a reverse type!
1422 *
1423 * We only do this if sanitizer edit_count is zero. Otherwise,
1424 * some of the subtables might have become insane after they
1425 * were sanity-checked by the edits of subsequent subtables.
1426 * https://bugs.chromium.org/p/chromium/issues/detail?id=960331
1427 */
1428 unsigned int type = get_subtable<TSubTable> (0).u.extension.get_type ();
1429 for (unsigned int i = 1; i < subtables; i++)
1430 if (get_subtable<TSubTable> (i).u.extension.get_type () != type)
1431 return_trace (false);
1432 }
1433 return_trace (true);
1434 }
1435
1436 protected:
1437 HBUINT16 lookupType; /* Different enumerations for GSUB and GPOS */
1438 HBUINT16 lookupFlag; /* Lookup qualifiers */
1439 Array16Of<Offset16>
1440 subTable; /* Array of SubTables */
1441/*HBUINT16 markFilteringSetX[HB_VAR_ARRAY];*//* Index (base 0) into GDEF mark glyph sets
1442 * structure. This field is only present if bit
1443 * UseMarkFilteringSet of lookup flags is set. */
1444 public:
1445 DEFINE_SIZE_ARRAY (6, subTable);
1446};
1447
1448template <typename Types>
1449using LookupList = List16OfOffsetTo<Lookup, typename Types::HBUINT>;
1450
1451template <typename TLookup, typename OffsetType>
1452struct LookupOffsetList : List16OfOffsetTo<TLookup, OffsetType>
1453{
1454 bool subset (hb_subset_context_t *c,
1455 hb_subset_layout_context_t *l) const
1456 {
1457 TRACE_SUBSET (this);
1458 auto *out = c->serializer->start_embed (this);
1459 if (unlikely (!out || !c->serializer->extend_min (out))) return_trace (false);
1460
1461 + hb_enumerate (*this)
1462 | hb_filter (l->lookup_index_map, hb_first)
1463 | hb_map (hb_second)
1464 | hb_apply (subset_offset_array (c, *out, this))
1465 ;
1466 return_trace (true);
1467 }
1468
1469 bool sanitize (hb_sanitize_context_t *c) const
1470 {
1471 TRACE_SANITIZE (this);
1472 return_trace (List16OfOffset16To<TLookup>::sanitize (c, this));
1473 }
1474};
1475
1476
1477/*
1478 * Coverage Table
1479 */
1480
1481
1482static bool ClassDef_remap_and_serialize (hb_serialize_context_t *c,
1483 const hb_set_t &klasses,
1484 bool use_class_zero,
1485 hb_sorted_vector_t<hb_pair_t<hb_codepoint_t, hb_codepoint_t>> &glyph_and_klass, /* IN/OUT */
1486 hb_map_t *klass_map /*IN/OUT*/)
1487{
1488 if (!klass_map)
1489 return ClassDef_serialize (c, it: glyph_and_klass.iter ());
1490
1491 /* any glyph not assigned a class value falls into Class zero (0),
1492 * if any glyph assigned to class 0, remapping must start with 0->0*/
1493 if (!use_class_zero)
1494 klass_map->set (key: 0, value: 0);
1495
1496 unsigned idx = klass_map->has (key: 0) ? 1 : 0;
1497 for (const unsigned k: klasses)
1498 {
1499 if (klass_map->has (key: k)) continue;
1500 klass_map->set (key: k, value&: idx);
1501 idx++;
1502 }
1503
1504
1505 for (unsigned i = 0; i < glyph_and_klass.length; i++)
1506 {
1507 hb_codepoint_t klass = glyph_and_klass[i].second;
1508 glyph_and_klass[i].second = klass_map->get (key: klass);
1509 }
1510
1511 c->propagate_error (o1&: glyph_and_klass, os: klasses);
1512 return ClassDef_serialize (c, it: glyph_and_klass.iter ());
1513}
1514
1515/*
1516 * Class Definition Table
1517 */
1518
1519template <typename Types>
1520struct ClassDefFormat1_3
1521{
1522 friend struct ClassDef;
1523
1524 private:
1525 unsigned int get_class (hb_codepoint_t glyph_id) const
1526 {
1527 return classValue[(unsigned int) (glyph_id - startGlyph)];
1528 }
1529
1530 unsigned get_population () const
1531 {
1532 return classValue.len;
1533 }
1534
1535 template<typename Iterator,
1536 hb_requires (hb_is_sorted_source_of (Iterator, hb_codepoint_t))>
1537 bool serialize (hb_serialize_context_t *c,
1538 Iterator it)
1539 {
1540 TRACE_SERIALIZE (this);
1541 if (unlikely (!c->extend_min (this))) return_trace (false);
1542
1543 if (unlikely (!it))
1544 {
1545 classFormat = 1;
1546 startGlyph = 0;
1547 classValue.len = 0;
1548 return_trace (true);
1549 }
1550
1551 hb_codepoint_t glyph_min = (*it).first;
1552 hb_codepoint_t glyph_max = + it
1553 | hb_map (hb_first)
1554 | hb_reduce (hb_max, 0u);
1555 unsigned glyph_count = glyph_max - glyph_min + 1;
1556
1557 startGlyph = glyph_min;
1558 if (unlikely (!classValue.serialize (c, glyph_count))) return_trace (false);
1559 for (const hb_pair_t<hb_codepoint_t, uint32_t> gid_klass_pair : + it)
1560 {
1561 unsigned idx = gid_klass_pair.first - glyph_min;
1562 classValue[idx] = gid_klass_pair.second;
1563 }
1564 return_trace (true);
1565 }
1566
1567 bool subset (hb_subset_context_t *c,
1568 hb_map_t *klass_map = nullptr /*OUT*/,
1569 bool keep_empty_table = true,
1570 bool use_class_zero = true,
1571 const Coverage* glyph_filter = nullptr) const
1572 {
1573 TRACE_SUBSET (this);
1574 const hb_map_t &glyph_map = c->plan->glyph_map_gsub;
1575
1576 hb_sorted_vector_t<hb_pair_t<hb_codepoint_t, hb_codepoint_t>> glyph_and_klass;
1577 hb_set_t orig_klasses;
1578
1579 hb_codepoint_t start = startGlyph;
1580 hb_codepoint_t end = start + classValue.len;
1581
1582 for (const hb_codepoint_t gid : + hb_range (start, end))
1583 {
1584 hb_codepoint_t new_gid = glyph_map[gid];
1585 if (new_gid == HB_MAP_VALUE_INVALID) continue;
1586 if (glyph_filter && !glyph_filter->has(k: gid)) continue;
1587
1588 unsigned klass = classValue[gid - start];
1589 if (!klass) continue;
1590
1591 glyph_and_klass.push (v: hb_pair (a&: new_gid, b&: klass));
1592 orig_klasses.add (g: klass);
1593 }
1594
1595 unsigned glyph_count = glyph_filter
1596 ? hb_len (hb_iter (glyph_map.keys()) | hb_filter (glyph_filter))
1597 : glyph_map.get_population ();
1598 use_class_zero = use_class_zero && glyph_count <= glyph_and_klass.length;
1599 if (!ClassDef_remap_and_serialize (c: c->serializer,
1600 klasses: orig_klasses,
1601 use_class_zero,
1602 glyph_and_klass,
1603 klass_map))
1604 return_trace (false);
1605 return_trace (keep_empty_table || (bool) glyph_and_klass);
1606 }
1607
1608 bool sanitize (hb_sanitize_context_t *c) const
1609 {
1610 TRACE_SANITIZE (this);
1611 return_trace (c->check_struct (this) && classValue.sanitize (c));
1612 }
1613
1614 unsigned cost () const { return 1; }
1615
1616 template <typename set_t>
1617 bool collect_coverage (set_t *glyphs) const
1618 {
1619 unsigned int start = 0;
1620 unsigned int count = classValue.len;
1621 for (unsigned int i = 0; i < count; i++)
1622 {
1623 if (classValue[i])
1624 continue;
1625
1626 if (start != i)
1627 if (unlikely (!glyphs->add_range (startGlyph + start, startGlyph + i)))
1628 return false;
1629
1630 start = i + 1;
1631 }
1632 if (start != count)
1633 if (unlikely (!glyphs->add_range (startGlyph + start, startGlyph + count)))
1634 return false;
1635
1636 return true;
1637 }
1638
1639 template <typename set_t>
1640 bool collect_class (set_t *glyphs, unsigned klass) const
1641 {
1642 unsigned int count = classValue.len;
1643 for (unsigned int i = 0; i < count; i++)
1644 if (classValue[i] == klass) glyphs->add (startGlyph + i);
1645 return true;
1646 }
1647
1648 bool intersects (const hb_set_t *glyphs) const
1649 {
1650 hb_codepoint_t start = startGlyph;
1651 hb_codepoint_t end = startGlyph + classValue.len;
1652 for (hb_codepoint_t iter = startGlyph - 1;
1653 glyphs->next (codepoint: &iter) && iter < end;)
1654 if (classValue[iter - start]) return true;
1655 return false;
1656 }
1657 bool intersects_class (const hb_set_t *glyphs, uint16_t klass) const
1658 {
1659 unsigned int count = classValue.len;
1660 if (klass == 0)
1661 {
1662 /* Match if there's any glyph that is not listed! */
1663 hb_codepoint_t g = HB_SET_VALUE_INVALID;
1664 if (!glyphs->next (codepoint: &g)) return false;
1665 if (g < startGlyph) return true;
1666 g = startGlyph + count - 1;
1667 if (glyphs->next (codepoint: &g)) return true;
1668 /* Fall through. */
1669 }
1670 /* TODO Speed up, using set overlap first? */
1671 /* TODO(iter) Rewrite as dagger. */
1672 const HBUINT16 *arr = classValue.arrayZ;
1673 for (unsigned int i = 0; i < count; i++)
1674 if (arr[i] == klass && glyphs->has (k: startGlyph + i))
1675 return true;
1676 return false;
1677 }
1678
1679 void intersected_class_glyphs (const hb_set_t *glyphs, unsigned klass, hb_set_t *intersect_glyphs) const
1680 {
1681 unsigned count = classValue.len;
1682 if (klass == 0)
1683 {
1684 unsigned start_glyph = startGlyph;
1685 for (uint32_t g = HB_SET_VALUE_INVALID;
1686 glyphs->next (codepoint: &g) && g < start_glyph;)
1687 intersect_glyphs->add (g);
1688
1689 for (uint32_t g = startGlyph + count - 1;
1690 glyphs-> next (codepoint: &g);)
1691 intersect_glyphs->add (g);
1692
1693 return;
1694 }
1695
1696 for (unsigned i = 0; i < count; i++)
1697 if (classValue[i] == klass && glyphs->has (k: startGlyph + i))
1698 intersect_glyphs->add (g: startGlyph + i);
1699
1700#if 0
1701 /* The following implementation is faster asymptotically, but slower
1702 * in practice. */
1703 unsigned start_glyph = startGlyph;
1704 unsigned end_glyph = start_glyph + count;
1705 for (unsigned g = startGlyph - 1;
1706 glyphs->next (&g) && g < end_glyph;)
1707 if (classValue.arrayZ[g - start_glyph] == klass)
1708 intersect_glyphs->add (g);
1709#endif
1710 }
1711
1712 void intersected_classes (const hb_set_t *glyphs, hb_set_t *intersect_classes) const
1713 {
1714 if (glyphs->is_empty ()) return;
1715 hb_codepoint_t end_glyph = startGlyph + classValue.len - 1;
1716 if (glyphs->get_min () < startGlyph ||
1717 glyphs->get_max () > end_glyph)
1718 intersect_classes->add (g: 0);
1719
1720 for (const auto& _ : + hb_enumerate (classValue))
1721 {
1722 hb_codepoint_t g = startGlyph + _.first;
1723 if (glyphs->has (k: g))
1724 intersect_classes->add (g: _.second);
1725 }
1726 }
1727
1728 protected:
1729 HBUINT16 classFormat; /* Format identifier--format = 1 */
1730 typename Types::HBGlyphID
1731 startGlyph; /* First GlyphID of the classValueArray */
1732 typename Types::template ArrayOf<HBUINT16>
1733 classValue; /* Array of Class Values--one per GlyphID */
1734 public:
1735 DEFINE_SIZE_ARRAY (2 + 2 * Types::size, classValue);
1736};
1737
1738template <typename Types>
1739struct ClassDefFormat2_4
1740{
1741 friend struct ClassDef;
1742
1743 private:
1744 unsigned int get_class (hb_codepoint_t glyph_id) const
1745 {
1746 return rangeRecord.bsearch (glyph_id).value;
1747 }
1748
1749 unsigned get_population () const
1750 {
1751 typename Types::large_int ret = 0;
1752 for (const auto &r : rangeRecord)
1753 ret += r.get_population ();
1754 return ret > UINT_MAX ? UINT_MAX : (unsigned) ret;
1755 }
1756
1757 template<typename Iterator,
1758 hb_requires (hb_is_sorted_source_of (Iterator, hb_codepoint_t))>
1759 bool serialize (hb_serialize_context_t *c,
1760 Iterator it)
1761 {
1762 TRACE_SERIALIZE (this);
1763 if (unlikely (!c->extend_min (this))) return_trace (false);
1764
1765 if (unlikely (!it))
1766 {
1767 classFormat = 2;
1768 rangeRecord.len = 0;
1769 return_trace (true);
1770 }
1771
1772 unsigned unsorted = false;
1773 unsigned num_ranges = 1;
1774 hb_codepoint_t prev_gid = (*it).first;
1775 unsigned prev_klass = (*it).second;
1776
1777 RangeRecord<Types> range_rec;
1778 range_rec.first = prev_gid;
1779 range_rec.last = prev_gid;
1780 range_rec.value = prev_klass;
1781
1782 auto *record = c->copy (range_rec);
1783 if (unlikely (!record)) return_trace (false);
1784
1785 for (const auto gid_klass_pair : + (++it))
1786 {
1787 hb_codepoint_t cur_gid = gid_klass_pair.first;
1788 unsigned cur_klass = gid_klass_pair.second;
1789
1790 if (cur_gid != prev_gid + 1 ||
1791 cur_klass != prev_klass)
1792 {
1793
1794 if (unlikely (cur_gid < prev_gid))
1795 unsorted = true;
1796
1797 if (unlikely (!record)) break;
1798 record->last = prev_gid;
1799 num_ranges++;
1800
1801 range_rec.first = cur_gid;
1802 range_rec.last = cur_gid;
1803 range_rec.value = cur_klass;
1804
1805 record = c->copy (range_rec);
1806 }
1807
1808 prev_klass = cur_klass;
1809 prev_gid = cur_gid;
1810 }
1811
1812 if (unlikely (c->in_error ())) return_trace (false);
1813
1814 if (likely (record)) record->last = prev_gid;
1815 rangeRecord.len = num_ranges;
1816
1817 if (unlikely (unsorted))
1818 rangeRecord.as_array ().qsort (RangeRecord<Types>::cmp_range);
1819
1820 return_trace (true);
1821 }
1822
1823 bool subset (hb_subset_context_t *c,
1824 hb_map_t *klass_map = nullptr /*OUT*/,
1825 bool keep_empty_table = true,
1826 bool use_class_zero = true,
1827 const Coverage* glyph_filter = nullptr) const
1828 {
1829 TRACE_SUBSET (this);
1830 const hb_map_t &glyph_map = c->plan->glyph_map_gsub;
1831 const hb_set_t &glyph_set = *c->plan->glyphset_gsub ();
1832
1833 hb_sorted_vector_t<hb_pair_t<hb_codepoint_t, hb_codepoint_t>> glyph_and_klass;
1834 hb_set_t orig_klasses;
1835
1836 if (glyph_set.get_population () * hb_bit_storage (v: (unsigned) rangeRecord.len) / 2
1837 < get_population ())
1838 {
1839 for (hb_codepoint_t g : glyph_set)
1840 {
1841 unsigned klass = get_class (glyph_id: g);
1842 if (!klass) continue;
1843 hb_codepoint_t new_gid = glyph_map[g];
1844 if (new_gid == HB_MAP_VALUE_INVALID) continue;
1845 if (glyph_filter && !glyph_filter->has (k: g)) continue;
1846 glyph_and_klass.push (v: hb_pair (a&: new_gid, b&: klass));
1847 orig_klasses.add (g: klass);
1848 }
1849 }
1850 else
1851 {
1852 unsigned num_source_glyphs = c->plan->source->get_num_glyphs ();
1853 for (auto &range : rangeRecord)
1854 {
1855 unsigned klass = range.value;
1856 if (!klass) continue;
1857 hb_codepoint_t start = range.first;
1858 hb_codepoint_t end = hb_min (range.last + 1, num_source_glyphs);
1859 for (hb_codepoint_t g = start; g < end; g++)
1860 {
1861 hb_codepoint_t new_gid = glyph_map[g];
1862 if (new_gid == HB_MAP_VALUE_INVALID) continue;
1863 if (glyph_filter && !glyph_filter->has (k: g)) continue;
1864
1865 glyph_and_klass.push (v: hb_pair (a&: new_gid, b&: klass));
1866 orig_klasses.add (g: klass);
1867 }
1868 }
1869 }
1870
1871 const hb_set_t& glyphset = *c->plan->glyphset_gsub ();
1872 unsigned glyph_count = glyph_filter
1873 ? hb_len (hb_iter (glyphset) | hb_filter (glyph_filter))
1874 : glyph_map.get_population ();
1875 use_class_zero = use_class_zero && glyph_count <= glyph_and_klass.length;
1876 if (!ClassDef_remap_and_serialize (c: c->serializer,
1877 klasses: orig_klasses,
1878 use_class_zero,
1879 glyph_and_klass,
1880 klass_map))
1881 return_trace (false);
1882 return_trace (keep_empty_table || (bool) glyph_and_klass);
1883 }
1884
1885 bool sanitize (hb_sanitize_context_t *c) const
1886 {
1887 TRACE_SANITIZE (this);
1888 return_trace (rangeRecord.sanitize (c));
1889 }
1890
1891 unsigned cost () const { return hb_bit_storage (v: (unsigned) rangeRecord.len); /* bsearch cost */ }
1892
1893 template <typename set_t>
1894 bool collect_coverage (set_t *glyphs) const
1895 {
1896 for (auto &range : rangeRecord)
1897 if (range.value)
1898 if (unlikely (!range.collect_coverage (glyphs)))
1899 return false;
1900 return true;
1901 }
1902
1903 template <typename set_t>
1904 bool collect_class (set_t *glyphs, unsigned int klass) const
1905 {
1906 for (auto &range : rangeRecord)
1907 {
1908 if (range.value == klass)
1909 if (unlikely (!range.collect_coverage (glyphs)))
1910 return false;
1911 }
1912 return true;
1913 }
1914
1915 bool intersects (const hb_set_t *glyphs) const
1916 {
1917 if (rangeRecord.len > glyphs->get_population () * hb_bit_storage (v: (unsigned) rangeRecord.len) / 2)
1918 {
1919 for (hb_codepoint_t g = HB_SET_VALUE_INVALID; glyphs->next (codepoint: &g);)
1920 if (get_class (glyph_id: g))
1921 return true;
1922 return false;
1923 }
1924
1925 return hb_any (+ hb_iter (rangeRecord)
1926 | hb_map ([glyphs] (const RangeRecord<Types> &range) { return range.intersects (*glyphs) && range.value; }));
1927 }
1928 bool intersects_class (const hb_set_t *glyphs, uint16_t klass) const
1929 {
1930 if (klass == 0)
1931 {
1932 /* Match if there's any glyph that is not listed! */
1933 hb_codepoint_t g = HB_SET_VALUE_INVALID;
1934 for (auto &range : rangeRecord)
1935 {
1936 if (!glyphs->next (codepoint: &g))
1937 break;
1938 if (g < range.first)
1939 return true;
1940 g = range.last;
1941 }
1942 if (g != HB_SET_VALUE_INVALID && glyphs->next (codepoint: &g))
1943 return true;
1944 /* Fall through. */
1945 }
1946 for (const auto &range : rangeRecord)
1947 if (range.value == klass && range.intersects (*glyphs))
1948 return true;
1949 return false;
1950 }
1951
1952 void intersected_class_glyphs (const hb_set_t *glyphs, unsigned klass, hb_set_t *intersect_glyphs) const
1953 {
1954 if (klass == 0)
1955 {
1956 hb_codepoint_t g = HB_SET_VALUE_INVALID;
1957 for (auto &range : rangeRecord)
1958 {
1959 if (!glyphs->next (codepoint: &g))
1960 goto done;
1961 while (g < range.first)
1962 {
1963 intersect_glyphs->add (g);
1964 if (!glyphs->next (codepoint: &g))
1965 goto done;
1966 }
1967 g = range.last;
1968 }
1969 while (glyphs->next (codepoint: &g))
1970 intersect_glyphs->add (g);
1971 done:
1972
1973 return;
1974 }
1975
1976 unsigned count = rangeRecord.len;
1977 if (count > glyphs->get_population () * hb_bit_storage (v: count) * 8)
1978 {
1979 for (hb_codepoint_t g = HB_SET_VALUE_INVALID;
1980 glyphs->next (codepoint: &g);)
1981 {
1982 unsigned i;
1983 if (rangeRecord.as_array ().bfind (g, &i) &&
1984 rangeRecord.arrayZ[i].value == klass)
1985 intersect_glyphs->add (g);
1986 }
1987 return;
1988 }
1989
1990 for (auto &range : rangeRecord)
1991 {
1992 if (range.value != klass) continue;
1993
1994 unsigned end = range.last + 1;
1995 for (hb_codepoint_t g = range.first - 1;
1996 glyphs->next (codepoint: &g) && g < end;)
1997 intersect_glyphs->add (g);
1998 }
1999 }
2000
2001 void intersected_classes (const hb_set_t *glyphs, hb_set_t *intersect_classes) const
2002 {
2003 if (glyphs->is_empty ()) return;
2004
2005 hb_codepoint_t g = HB_SET_VALUE_INVALID;
2006 for (auto &range : rangeRecord)
2007 {
2008 if (!glyphs->next (codepoint: &g))
2009 break;
2010 if (g < range.first)
2011 {
2012 intersect_classes->add (g: 0);
2013 break;
2014 }
2015 g = range.last;
2016 }
2017 if (g != HB_SET_VALUE_INVALID && glyphs->next (codepoint: &g))
2018 intersect_classes->add (g: 0);
2019
2020 for (const auto& range : rangeRecord)
2021 if (range.intersects (*glyphs))
2022 intersect_classes->add (g: range.value);
2023 }
2024
2025 protected:
2026 HBUINT16 classFormat; /* Format identifier--format = 2 */
2027 typename Types::template SortedArrayOf<RangeRecord<Types>>
2028 rangeRecord; /* Array of glyph ranges--ordered by
2029 * Start GlyphID */
2030 public:
2031 DEFINE_SIZE_ARRAY (2 + Types::size, rangeRecord);
2032};
2033
2034struct ClassDef
2035{
2036 /* Has interface. */
2037 unsigned operator [] (hb_codepoint_t k) const { return get (k); }
2038 bool has (hb_codepoint_t k) const { return (*this)[k]; }
2039 /* Projection. */
2040 hb_codepoint_t operator () (hb_codepoint_t k) const { return get (k); }
2041
2042 unsigned int get (hb_codepoint_t k) const { return get_class (glyph_id: k); }
2043 unsigned int get_class (hb_codepoint_t glyph_id) const
2044 {
2045 switch (u.format) {
2046 case 1: return u.format1.get_class (glyph_id);
2047 case 2: return u.format2.get_class (glyph_id);
2048#ifndef HB_NO_BEYOND_64K
2049 case 3: return u.format3.get_class (glyph_id);
2050 case 4: return u.format4.get_class (glyph_id);
2051#endif
2052 default:return 0;
2053 }
2054 }
2055
2056 unsigned get_population () const
2057 {
2058 switch (u.format) {
2059 case 1: return u.format1.get_population ();
2060 case 2: return u.format2.get_population ();
2061#ifndef HB_NO_BEYOND_64K
2062 case 3: return u.format3.get_population ();
2063 case 4: return u.format4.get_population ();
2064#endif
2065 default:return NOT_COVERED;
2066 }
2067 }
2068
2069 template<typename Iterator,
2070 hb_requires (hb_is_sorted_source_of (Iterator, hb_codepoint_t))>
2071 bool serialize (hb_serialize_context_t *c, Iterator it_with_class_zero)
2072 {
2073 TRACE_SERIALIZE (this);
2074 if (unlikely (!c->extend_min (this))) return_trace (false);
2075
2076 auto it = + it_with_class_zero | hb_filter (hb_second);
2077
2078 unsigned format = 2;
2079 hb_codepoint_t glyph_max = 0;
2080 if (likely (it))
2081 {
2082 hb_codepoint_t glyph_min = (*it).first;
2083 glyph_max = glyph_min;
2084
2085 unsigned num_glyphs = 0;
2086 unsigned num_ranges = 1;
2087 hb_codepoint_t prev_gid = glyph_min;
2088 unsigned prev_klass = (*it).second;
2089
2090 for (const auto gid_klass_pair : it)
2091 {
2092 hb_codepoint_t cur_gid = gid_klass_pair.first;
2093 unsigned cur_klass = gid_klass_pair.second;
2094 num_glyphs++;
2095 if (cur_gid == glyph_min) continue;
2096 if (cur_gid > glyph_max) glyph_max = cur_gid;
2097 if (cur_gid != prev_gid + 1 ||
2098 cur_klass != prev_klass)
2099 num_ranges++;
2100
2101 prev_gid = cur_gid;
2102 prev_klass = cur_klass;
2103 }
2104
2105 if (num_glyphs && 1 + (glyph_max - glyph_min + 1) <= num_ranges * 3)
2106 format = 1;
2107 }
2108
2109#ifndef HB_NO_BEYOND_64K
2110 if (glyph_max > 0xFFFFu)
2111 u.format += 2;
2112 if (unlikely (glyph_max > 0xFFFFFFu))
2113#else
2114 if (unlikely (glyph_max > 0xFFFFu))
2115#endif
2116 {
2117 c->check_success (success: false, err_type: HB_SERIALIZE_ERROR_INT_OVERFLOW);
2118 return_trace (false);
2119 }
2120
2121 u.format = format;
2122
2123 switch (u.format)
2124 {
2125 case 1: return_trace (u.format1.serialize (c, it));
2126 case 2: return_trace (u.format2.serialize (c, it));
2127#ifndef HB_NO_BEYOND_64K
2128 case 3: return_trace (u.format3.serialize (c, it));
2129 case 4: return_trace (u.format4.serialize (c, it));
2130#endif
2131 default:return_trace (false);
2132 }
2133 }
2134
2135 bool subset (hb_subset_context_t *c,
2136 hb_map_t *klass_map = nullptr /*OUT*/,
2137 bool keep_empty_table = true,
2138 bool use_class_zero = true,
2139 const Coverage* glyph_filter = nullptr) const
2140 {
2141 TRACE_SUBSET (this);
2142 switch (u.format) {
2143 case 1: return_trace (u.format1.subset (c, klass_map, keep_empty_table, use_class_zero, glyph_filter));
2144 case 2: return_trace (u.format2.subset (c, klass_map, keep_empty_table, use_class_zero, glyph_filter));
2145#ifndef HB_NO_BEYOND_64K
2146 case 3: return_trace (u.format3.subset (c, klass_map, keep_empty_table, use_class_zero, glyph_filter));
2147 case 4: return_trace (u.format4.subset (c, klass_map, keep_empty_table, use_class_zero, glyph_filter));
2148#endif
2149 default:return_trace (false);
2150 }
2151 }
2152
2153 bool sanitize (hb_sanitize_context_t *c) const
2154 {
2155 TRACE_SANITIZE (this);
2156 if (!u.format.sanitize (c)) return_trace (false);
2157 switch (u.format) {
2158 case 1: return_trace (u.format1.sanitize (c));
2159 case 2: return_trace (u.format2.sanitize (c));
2160#ifndef HB_NO_BEYOND_64K
2161 case 3: return_trace (u.format3.sanitize (c));
2162 case 4: return_trace (u.format4.sanitize (c));
2163#endif
2164 default:return_trace (true);
2165 }
2166 }
2167
2168 unsigned cost () const
2169 {
2170 switch (u.format) {
2171 case 1: return u.format1.cost ();
2172 case 2: return u.format2.cost ();
2173#ifndef HB_NO_BEYOND_64K
2174 case 3: return u.format3.cost ();
2175 case 4: return u.format4.cost ();
2176#endif
2177 default:return 0u;
2178 }
2179 }
2180
2181 /* Might return false if array looks unsorted.
2182 * Used for faster rejection of corrupt data. */
2183 template <typename set_t>
2184 bool collect_coverage (set_t *glyphs) const
2185 {
2186 switch (u.format) {
2187 case 1: return u.format1.collect_coverage (glyphs);
2188 case 2: return u.format2.collect_coverage (glyphs);
2189#ifndef HB_NO_BEYOND_64K
2190 case 3: return u.format3.collect_coverage (glyphs);
2191 case 4: return u.format4.collect_coverage (glyphs);
2192#endif
2193 default:return false;
2194 }
2195 }
2196
2197 /* Might return false if array looks unsorted.
2198 * Used for faster rejection of corrupt data. */
2199 template <typename set_t>
2200 bool collect_class (set_t *glyphs, unsigned int klass) const
2201 {
2202 switch (u.format) {
2203 case 1: return u.format1.collect_class (glyphs, klass);
2204 case 2: return u.format2.collect_class (glyphs, klass);
2205#ifndef HB_NO_BEYOND_64K
2206 case 3: return u.format3.collect_class (glyphs, klass);
2207 case 4: return u.format4.collect_class (glyphs, klass);
2208#endif
2209 default:return false;
2210 }
2211 }
2212
2213 bool intersects (const hb_set_t *glyphs) const
2214 {
2215 switch (u.format) {
2216 case 1: return u.format1.intersects (glyphs);
2217 case 2: return u.format2.intersects (glyphs);
2218#ifndef HB_NO_BEYOND_64K
2219 case 3: return u.format3.intersects (glyphs);
2220 case 4: return u.format4.intersects (glyphs);
2221#endif
2222 default:return false;
2223 }
2224 }
2225 bool intersects_class (const hb_set_t *glyphs, unsigned int klass) const
2226 {
2227 switch (u.format) {
2228 case 1: return u.format1.intersects_class (glyphs, klass);
2229 case 2: return u.format2.intersects_class (glyphs, klass);
2230#ifndef HB_NO_BEYOND_64K
2231 case 3: return u.format3.intersects_class (glyphs, klass);
2232 case 4: return u.format4.intersects_class (glyphs, klass);
2233#endif
2234 default:return false;
2235 }
2236 }
2237
2238 void intersected_class_glyphs (const hb_set_t *glyphs, unsigned klass, hb_set_t *intersect_glyphs) const
2239 {
2240 switch (u.format) {
2241 case 1: return u.format1.intersected_class_glyphs (glyphs, klass, intersect_glyphs);
2242 case 2: return u.format2.intersected_class_glyphs (glyphs, klass, intersect_glyphs);
2243#ifndef HB_NO_BEYOND_64K
2244 case 3: return u.format3.intersected_class_glyphs (glyphs, klass, intersect_glyphs);
2245 case 4: return u.format4.intersected_class_glyphs (glyphs, klass, intersect_glyphs);
2246#endif
2247 default:return;
2248 }
2249 }
2250
2251 void intersected_classes (const hb_set_t *glyphs, hb_set_t *intersect_classes) const
2252 {
2253 switch (u.format) {
2254 case 1: return u.format1.intersected_classes (glyphs, intersect_classes);
2255 case 2: return u.format2.intersected_classes (glyphs, intersect_classes);
2256#ifndef HB_NO_BEYOND_64K
2257 case 3: return u.format3.intersected_classes (glyphs, intersect_classes);
2258 case 4: return u.format4.intersected_classes (glyphs, intersect_classes);
2259#endif
2260 default:return;
2261 }
2262 }
2263
2264
2265 protected:
2266 union {
2267 HBUINT16 format; /* Format identifier */
2268 ClassDefFormat1_3<SmallTypes> format1;
2269 ClassDefFormat2_4<SmallTypes> format2;
2270#ifndef HB_NO_BEYOND_64K
2271 ClassDefFormat1_3<MediumTypes>format3;
2272 ClassDefFormat2_4<MediumTypes>format4;
2273#endif
2274 } u;
2275 public:
2276 DEFINE_SIZE_UNION (2, format);
2277};
2278
2279template<typename Iterator>
2280static inline bool ClassDef_serialize (hb_serialize_context_t *c,
2281 Iterator it)
2282{ return (c->start_embed<ClassDef> ()->serialize (c, it)); }
2283
2284
2285/*
2286 * Item Variation Store
2287 */
2288
2289struct VarRegionAxis
2290{
2291 float evaluate (int coord) const
2292 {
2293 int peak = peakCoord.to_int ();
2294 if (peak == 0 || coord == peak)
2295 return 1.f;
2296
2297 int start = startCoord.to_int (), end = endCoord.to_int ();
2298
2299 /* TODO Move these to sanitize(). */
2300 if (unlikely (start > peak || peak > end))
2301 return 1.f;
2302 if (unlikely (start < 0 && end > 0 && peak != 0))
2303 return 1.f;
2304
2305 if (coord <= start || end <= coord)
2306 return 0.f;
2307
2308 /* Interpolate */
2309 if (coord < peak)
2310 return float (coord - start) / (peak - start);
2311 else
2312 return float (end - coord) / (end - peak);
2313 }
2314
2315 bool sanitize (hb_sanitize_context_t *c) const
2316 {
2317 TRACE_SANITIZE (this);
2318 return_trace (c->check_struct (this));
2319 /* TODO Handle invalid start/peak/end configs, so we don't
2320 * have to do that at runtime. */
2321 }
2322
2323 public:
2324 F2DOT14 startCoord;
2325 F2DOT14 peakCoord;
2326 F2DOT14 endCoord;
2327 public:
2328 DEFINE_SIZE_STATIC (6);
2329};
2330
2331#define REGION_CACHE_ITEM_CACHE_INVALID 2.f
2332
2333struct VarRegionList
2334{
2335 using cache_t = float;
2336
2337 float evaluate (unsigned int region_index,
2338 const int *coords, unsigned int coord_len,
2339 cache_t *cache = nullptr) const
2340 {
2341 if (unlikely (region_index >= regionCount))
2342 return 0.;
2343
2344 float *cached_value = nullptr;
2345 if (cache)
2346 {
2347 cached_value = &(cache[region_index]);
2348 if (likely (*cached_value != REGION_CACHE_ITEM_CACHE_INVALID))
2349 return *cached_value;
2350 }
2351
2352 const VarRegionAxis *axes = axesZ.arrayZ + (region_index * axisCount);
2353
2354 float v = 1.;
2355 unsigned int count = axisCount;
2356 for (unsigned int i = 0; i < count; i++)
2357 {
2358 int coord = i < coord_len ? coords[i] : 0;
2359 float factor = axes[i].evaluate (coord);
2360 if (factor == 0.f)
2361 {
2362 if (cache)
2363 *cached_value = 0.;
2364 return 0.;
2365 }
2366 v *= factor;
2367 }
2368
2369 if (cache)
2370 *cached_value = v;
2371 return v;
2372 }
2373
2374 bool sanitize (hb_sanitize_context_t *c) const
2375 {
2376 TRACE_SANITIZE (this);
2377 return_trace (c->check_struct (this) && axesZ.sanitize (c, axisCount * regionCount));
2378 }
2379
2380 bool serialize (hb_serialize_context_t *c, const VarRegionList *src, const hb_bimap_t &region_map)
2381 {
2382 TRACE_SERIALIZE (this);
2383 if (unlikely (!c->extend_min (this))) return_trace (false);
2384 axisCount = src->axisCount;
2385 regionCount = region_map.get_population ();
2386 if (unlikely (hb_unsigned_mul_overflows (axisCount * regionCount,
2387 VarRegionAxis::static_size))) return_trace (false);
2388 if (unlikely (!c->extend (this))) return_trace (false);
2389 unsigned int region_count = src->regionCount;
2390 for (unsigned int r = 0; r < regionCount; r++)
2391 {
2392 unsigned int backward = region_map.backward (rhs: r);
2393 if (backward >= region_count) return_trace (false);
2394 hb_memcpy (dst: &axesZ[axisCount * r], src: &src->axesZ[axisCount * backward], len: VarRegionAxis::static_size * axisCount);
2395 }
2396
2397 return_trace (true);
2398 }
2399
2400 unsigned int get_size () const { return min_size + VarRegionAxis::static_size * axisCount * regionCount; }
2401
2402 public:
2403 HBUINT16 axisCount;
2404 HBUINT15 regionCount;
2405 protected:
2406 UnsizedArrayOf<VarRegionAxis>
2407 axesZ;
2408 public:
2409 DEFINE_SIZE_ARRAY (4, axesZ);
2410};
2411
2412struct VarData
2413{
2414 unsigned int get_item_count () const
2415 { return itemCount; }
2416
2417 unsigned int get_region_index_count () const
2418 { return regionIndices.len; }
2419
2420 unsigned int get_row_size () const
2421 { return (wordCount () + regionIndices.len) * (longWords () ? 2 : 1); }
2422
2423 unsigned int get_size () const
2424 { return min_size
2425 - regionIndices.min_size + regionIndices.get_size ()
2426 + itemCount * get_row_size ();
2427 }
2428
2429 float get_delta (unsigned int inner,
2430 const int *coords, unsigned int coord_count,
2431 const VarRegionList &regions,
2432 VarRegionList::cache_t *cache = nullptr) const
2433 {
2434 if (unlikely (inner >= itemCount))
2435 return 0.;
2436
2437 unsigned int count = regionIndices.len;
2438 bool is_long = longWords ();
2439 unsigned word_count = wordCount ();
2440 unsigned int scount = is_long ? count : word_count;
2441 unsigned int lcount = is_long ? word_count : 0;
2442
2443 const HBUINT8 *bytes = get_delta_bytes ();
2444 const HBUINT8 *row = bytes + inner * get_row_size ();
2445
2446 float delta = 0.;
2447 unsigned int i = 0;
2448
2449 const HBINT32 *lcursor = reinterpret_cast<const HBINT32 *> (row);
2450 for (; i < lcount; i++)
2451 {
2452 float scalar = regions.evaluate (region_index: regionIndices.arrayZ[i], coords, coord_len: coord_count, cache);
2453 delta += scalar * *lcursor++;
2454 }
2455 const HBINT16 *scursor = reinterpret_cast<const HBINT16 *> (lcursor);
2456 for (; i < scount; i++)
2457 {
2458 float scalar = regions.evaluate (region_index: regionIndices.arrayZ[i], coords, coord_len: coord_count, cache);
2459 delta += scalar * *scursor++;
2460 }
2461 const HBINT8 *bcursor = reinterpret_cast<const HBINT8 *> (scursor);
2462 for (; i < count; i++)
2463 {
2464 float scalar = regions.evaluate (region_index: regionIndices.arrayZ[i], coords, coord_len: coord_count, cache);
2465 delta += scalar * *bcursor++;
2466 }
2467
2468 return delta;
2469 }
2470
2471 void get_region_scalars (const int *coords, unsigned int coord_count,
2472 const VarRegionList &regions,
2473 float *scalars /*OUT */,
2474 unsigned int num_scalars) const
2475 {
2476 unsigned count = hb_min (num_scalars, regionIndices.len);
2477 for (unsigned int i = 0; i < count; i++)
2478 scalars[i] = regions.evaluate (region_index: regionIndices.arrayZ[i], coords, coord_len: coord_count);
2479 for (unsigned int i = count; i < num_scalars; i++)
2480 scalars[i] = 0.f;
2481 }
2482
2483 bool sanitize (hb_sanitize_context_t *c) const
2484 {
2485 TRACE_SANITIZE (this);
2486 return_trace (c->check_struct (this) &&
2487 regionIndices.sanitize (c) &&
2488 wordCount () <= regionIndices.len &&
2489 c->check_range (get_delta_bytes (),
2490 itemCount,
2491 get_row_size ()));
2492 }
2493
2494 bool serialize (hb_serialize_context_t *c,
2495 const VarData *src,
2496 const hb_inc_bimap_t &inner_map,
2497 const hb_bimap_t &region_map)
2498 {
2499 TRACE_SERIALIZE (this);
2500 if (unlikely (!c->extend_min (this))) return_trace (false);
2501 itemCount = inner_map.get_next_value ();
2502
2503 /* Optimize word count */
2504 unsigned ri_count = src->regionIndices.len;
2505 enum delta_size_t { kZero=0, kNonWord, kWord };
2506 hb_vector_t<delta_size_t> delta_sz;
2507 hb_vector_t<unsigned int> ri_map; /* maps new index to old index */
2508 delta_sz.resize (size_: ri_count);
2509 ri_map.resize (size_: ri_count);
2510 unsigned int new_word_count = 0;
2511 unsigned int r;
2512
2513 const HBUINT8 *src_delta_bytes = src->get_delta_bytes ();
2514 unsigned src_row_size = src->get_row_size ();
2515 unsigned src_word_count = src->wordCount ();
2516 bool src_long_words = src->longWords ();
2517
2518 bool has_long = false;
2519 if (src_long_words)
2520 {
2521 for (r = 0; r < src_word_count; r++)
2522 {
2523 for (unsigned old_gid : inner_map.keys())
2524 {
2525 int32_t delta = src->get_item_delta_fast (item: old_gid, region: r, delta_bytes: src_delta_bytes, row_size: src_row_size);
2526 if (delta < -65536 || 65535 < delta)
2527 {
2528 has_long = true;
2529 break;
2530 }
2531 }
2532 }
2533 }
2534
2535 signed min_threshold = has_long ? -65536 : -128;
2536 signed max_threshold = has_long ? +65535 : +127;
2537 for (r = 0; r < ri_count; r++)
2538 {
2539 bool short_circuit = src_long_words == has_long && src_word_count <= r;
2540
2541 delta_sz[r] = kZero;
2542 for (unsigned old_gid : inner_map.keys())
2543 {
2544 int32_t delta = src->get_item_delta_fast (item: old_gid, region: r, delta_bytes: src_delta_bytes, row_size: src_row_size);
2545 if (delta < min_threshold || max_threshold < delta)
2546 {
2547 delta_sz[r] = kWord;
2548 new_word_count++;
2549 break;
2550 }
2551 else if (delta != 0)
2552 {
2553 delta_sz[r] = kNonWord;
2554 if (short_circuit)
2555 break;
2556 }
2557 }
2558 }
2559
2560 unsigned int word_index = 0;
2561 unsigned int non_word_index = new_word_count;
2562 unsigned int new_ri_count = 0;
2563 for (r = 0; r < ri_count; r++)
2564 if (delta_sz[r])
2565 {
2566 unsigned new_r = (delta_sz[r] == kWord)? word_index++ : non_word_index++;
2567 ri_map[new_r] = r;
2568 new_ri_count++;
2569 }
2570
2571 wordSizeCount = new_word_count | (has_long ? 0x8000u /* LONG_WORDS */ : 0);
2572
2573 regionIndices.len = new_ri_count;
2574
2575 if (unlikely (!c->extend (this))) return_trace (false);
2576
2577 for (r = 0; r < new_ri_count; r++)
2578 regionIndices[r] = region_map[src->regionIndices[ri_map[r]]];
2579
2580 HBUINT8 *delta_bytes = get_delta_bytes ();
2581 unsigned row_size = get_row_size ();
2582 unsigned count = itemCount;
2583 for (unsigned int i = 0; i < count; i++)
2584 {
2585 unsigned int old = inner_map.backward (rhs: i);
2586 for (unsigned int r = 0; r < new_ri_count; r++)
2587 set_item_delta_fast (item: i, region: r,
2588 delta: src->get_item_delta_fast (item: old, region: ri_map[r],
2589 delta_bytes: src_delta_bytes, row_size: src_row_size),
2590 delta_bytes, row_size);
2591 }
2592
2593 return_trace (true);
2594 }
2595
2596 void collect_region_refs (hb_set_t &region_indices, const hb_inc_bimap_t &inner_map) const
2597 {
2598 const HBUINT8 *delta_bytes = get_delta_bytes ();
2599 unsigned row_size = get_row_size ();
2600
2601 for (unsigned int r = 0; r < regionIndices.len; r++)
2602 {
2603 unsigned int region = regionIndices.arrayZ[r];
2604 if (region_indices.has (k: region)) continue;
2605 for (hb_codepoint_t old_gid : inner_map.keys())
2606 if (get_item_delta_fast (item: old_gid, region: r, delta_bytes, row_size) != 0)
2607 {
2608 region_indices.add (g: region);
2609 break;
2610 }
2611 }
2612 }
2613
2614 protected:
2615 const HBUINT8 *get_delta_bytes () const
2616 { return &StructAfter<HBUINT8> (X: regionIndices); }
2617
2618 HBUINT8 *get_delta_bytes ()
2619 { return &StructAfter<HBUINT8> (X&: regionIndices); }
2620
2621 int32_t get_item_delta_fast (unsigned int item, unsigned int region,
2622 const HBUINT8 *delta_bytes, unsigned row_size) const
2623 {
2624 if (unlikely (item >= itemCount || region >= regionIndices.len)) return 0;
2625
2626 const HBINT8 *p = (const HBINT8 *) delta_bytes + item * row_size;
2627 unsigned word_count = wordCount ();
2628 bool is_long = longWords ();
2629 if (is_long)
2630 {
2631 if (region < word_count)
2632 return ((const HBINT32 *) p)[region];
2633 else
2634 return ((const HBINT16 *)(p + HBINT32::static_size * word_count))[region - word_count];
2635 }
2636 else
2637 {
2638 if (region < word_count)
2639 return ((const HBINT16 *) p)[region];
2640 else
2641 return (p + HBINT16::static_size * word_count)[region - word_count];
2642 }
2643 }
2644 int32_t get_item_delta (unsigned int item, unsigned int region) const
2645 {
2646 return get_item_delta_fast (item, region,
2647 delta_bytes: get_delta_bytes (),
2648 row_size: get_row_size ());
2649 }
2650
2651 void set_item_delta_fast (unsigned int item, unsigned int region, int32_t delta,
2652 HBUINT8 *delta_bytes, unsigned row_size)
2653 {
2654 HBINT8 *p = (HBINT8 *) delta_bytes + item * row_size;
2655 unsigned word_count = wordCount ();
2656 bool is_long = longWords ();
2657 if (is_long)
2658 {
2659 if (region < word_count)
2660 ((HBINT32 *) p)[region] = delta;
2661 else
2662 ((HBINT16 *)(p + HBINT32::static_size * word_count))[region - word_count] = delta;
2663 }
2664 else
2665 {
2666 if (region < word_count)
2667 ((HBINT16 *) p)[region] = delta;
2668 else
2669 (p + HBINT16::static_size * word_count)[region - word_count] = delta;
2670 }
2671 }
2672 void set_item_delta (unsigned int item, unsigned int region, int32_t delta)
2673 {
2674 set_item_delta_fast (item, region, delta,
2675 delta_bytes: get_delta_bytes (),
2676 row_size: get_row_size ());
2677 }
2678
2679 bool longWords () const { return wordSizeCount & 0x8000u /* LONG_WORDS */; }
2680 unsigned wordCount () const { return wordSizeCount & 0x7FFFu /* WORD_DELTA_COUNT_MASK */; }
2681
2682 protected:
2683 HBUINT16 itemCount;
2684 HBUINT16 wordSizeCount;
2685 Array16Of<HBUINT16> regionIndices;
2686/*UnsizedArrayOf<HBUINT8>bytesX;*/
2687 public:
2688 DEFINE_SIZE_ARRAY (6, regionIndices);
2689};
2690
2691struct VariationStore
2692{
2693 using cache_t = VarRegionList::cache_t;
2694
2695 cache_t *create_cache () const
2696 {
2697#ifdef HB_NO_VAR
2698 return nullptr;
2699#endif
2700 auto &r = this+regions;
2701 unsigned count = r.regionCount;
2702
2703 float *cache = (float *) hb_malloc (size: sizeof (float) * count);
2704 if (unlikely (!cache)) return nullptr;
2705
2706 for (unsigned i = 0; i < count; i++)
2707 cache[i] = REGION_CACHE_ITEM_CACHE_INVALID;
2708
2709 return cache;
2710 }
2711
2712 static void destroy_cache (cache_t *cache) { hb_free (ptr: cache); }
2713
2714 private:
2715 float get_delta (unsigned int outer, unsigned int inner,
2716 const int *coords, unsigned int coord_count,
2717 VarRegionList::cache_t *cache = nullptr) const
2718 {
2719#ifdef HB_NO_VAR
2720 return 0.f;
2721#endif
2722
2723 if (unlikely (outer >= dataSets.len))
2724 return 0.f;
2725
2726 return (this+dataSets[outer]).get_delta (inner,
2727 coords, coord_count,
2728 regions: this+regions,
2729 cache);
2730 }
2731
2732 public:
2733 float get_delta (unsigned int index,
2734 const int *coords, unsigned int coord_count,
2735 VarRegionList::cache_t *cache = nullptr) const
2736 {
2737 unsigned int outer = index >> 16;
2738 unsigned int inner = index & 0xFFFF;
2739 return get_delta (outer, inner, coords, coord_count, cache);
2740 }
2741 float get_delta (unsigned int index,
2742 hb_array_t<int> coords,
2743 VarRegionList::cache_t *cache = nullptr) const
2744 {
2745 return get_delta (index,
2746 coords: coords.arrayZ, coord_count: coords.length,
2747 cache);
2748 }
2749
2750 bool sanitize (hb_sanitize_context_t *c) const
2751 {
2752#ifdef HB_NO_VAR
2753 return true;
2754#endif
2755
2756 TRACE_SANITIZE (this);
2757 return_trace (c->check_struct (this) &&
2758 format == 1 &&
2759 regions.sanitize (c, this) &&
2760 dataSets.sanitize (c, this));
2761 }
2762
2763 bool serialize (hb_serialize_context_t *c,
2764 const VariationStore *src,
2765 const hb_array_t <const hb_inc_bimap_t> &inner_maps)
2766 {
2767 TRACE_SERIALIZE (this);
2768#ifdef HB_NO_VAR
2769 return_trace (false);
2770#endif
2771
2772 if (unlikely (!c->extend_min (this))) return_trace (false);
2773
2774 unsigned int set_count = 0;
2775 for (unsigned int i = 0; i < inner_maps.length; i++)
2776 if (inner_maps[i].get_population ())
2777 set_count++;
2778
2779 format = 1;
2780
2781 const auto &src_regions = src+src->regions;
2782
2783 hb_set_t region_indices;
2784 for (unsigned int i = 0; i < inner_maps.length; i++)
2785 (src+src->dataSets[i]).collect_region_refs (region_indices, inner_map: inner_maps[i]);
2786
2787 if (region_indices.in_error ())
2788 return_trace (false);
2789
2790 region_indices.del_range (a: (src_regions).regionCount, b: hb_set_t::INVALID);
2791
2792 /* TODO use constructor when our data-structures support that. */
2793 hb_inc_bimap_t region_map;
2794 + hb_iter (region_indices)
2795 | hb_apply ([&region_map] (unsigned _) { region_map.add(lhs: _); })
2796 ;
2797 if (region_map.in_error())
2798 return_trace (false);
2799
2800 if (unlikely (!regions.serialize_serialize (c, &src_regions, region_map)))
2801 return_trace (false);
2802
2803 dataSets.len = set_count;
2804 if (unlikely (!c->extend (dataSets))) return_trace (false);
2805
2806 /* TODO: The following code could be simplified when
2807 * List16OfOffset16To::subset () can take a custom param to be passed to VarData::serialize () */
2808 unsigned int set_index = 0;
2809 for (unsigned int i = 0; i < inner_maps.length; i++)
2810 {
2811 if (!inner_maps[i].get_population ()) continue;
2812 if (unlikely (!dataSets[set_index++]
2813 .serialize_serialize (c, &(src+src->dataSets[i]), inner_maps[i], region_map)))
2814 return_trace (false);
2815 }
2816
2817 return_trace (true);
2818 }
2819
2820 VariationStore *copy (hb_serialize_context_t *c) const
2821 {
2822 TRACE_SERIALIZE (this);
2823 auto *out = c->start_embed (obj: this);
2824 if (unlikely (!out)) return_trace (nullptr);
2825
2826 hb_vector_t <hb_inc_bimap_t> inner_maps;
2827 unsigned count = dataSets.len;
2828 for (unsigned i = 0; i < count; i++)
2829 {
2830 hb_inc_bimap_t *map = inner_maps.push ();
2831 auto &data = this+dataSets[i];
2832
2833 unsigned itemCount = data.get_item_count ();
2834 for (unsigned j = 0; j < itemCount; j++)
2835 map->add (lhs: j);
2836 }
2837
2838 if (unlikely (!out->serialize (c, this, inner_maps))) return_trace (nullptr);
2839
2840 return_trace (out);
2841 }
2842
2843 bool subset (hb_subset_context_t *c, const hb_array_t<const hb_inc_bimap_t> &inner_maps) const
2844 {
2845 TRACE_SUBSET (this);
2846#ifdef HB_NO_VAR
2847 return_trace (false);
2848#endif
2849
2850 VariationStore *varstore_prime = c->serializer->start_embed<VariationStore> ();
2851 if (unlikely (!varstore_prime)) return_trace (false);
2852
2853 varstore_prime->serialize (c: c->serializer, src: this, inner_maps);
2854
2855 return_trace (
2856 !c->serializer->in_error()
2857 && varstore_prime->dataSets);
2858 }
2859
2860 unsigned int get_region_index_count (unsigned int major) const
2861 {
2862#ifdef HB_NO_VAR
2863 return 0;
2864#endif
2865 return (this+dataSets[major]).get_region_index_count ();
2866 }
2867
2868 void get_region_scalars (unsigned int major,
2869 const int *coords, unsigned int coord_count,
2870 float *scalars /*OUT*/,
2871 unsigned int num_scalars) const
2872 {
2873#ifdef HB_NO_VAR
2874 for (unsigned i = 0; i < num_scalars; i++)
2875 scalars[i] = 0.f;
2876 return;
2877#endif
2878
2879 (this+dataSets[major]).get_region_scalars (coords, coord_count,
2880 regions: this+regions,
2881 scalars: &scalars[0], num_scalars);
2882 }
2883
2884 unsigned int get_sub_table_count () const
2885 {
2886#ifdef HB_NO_VAR
2887 return 0;
2888#endif
2889 return dataSets.len;
2890 }
2891
2892 protected:
2893 HBUINT16 format;
2894 Offset32To<VarRegionList> regions;
2895 Array16OfOffset32To<VarData> dataSets;
2896 public:
2897 DEFINE_SIZE_ARRAY_SIZED (8, dataSets);
2898};
2899
2900#undef REGION_CACHE_ITEM_CACHE_INVALID
2901
2902/*
2903 * Feature Variations
2904 */
2905enum Cond_with_Var_flag_t
2906{
2907 KEEP_COND_WITH_VAR = 0,
2908 DROP_COND_WITH_VAR = 1,
2909 DROP_RECORD_WITH_VAR = 2,
2910 MEM_ERR_WITH_VAR = 3,
2911};
2912
2913struct ConditionFormat1
2914{
2915 friend struct Condition;
2916
2917 bool subset (hb_subset_context_t *c) const
2918 {
2919 TRACE_SUBSET (this);
2920 auto *out = c->serializer->embed (obj: this);
2921 if (unlikely (!out)) return_trace (false);
2922
2923 const hb_map_t *index_map = &c->plan->axes_index_map;
2924 if (index_map->is_empty ()) return_trace (true);
2925
2926 if (!index_map->has (key: axisIndex))
2927 return_trace (false);
2928
2929 return_trace (c->serializer->check_assign (out->axisIndex, index_map->get (axisIndex),
2930 HB_SERIALIZE_ERROR_INT_OVERFLOW));
2931 }
2932
2933 private:
2934 Cond_with_Var_flag_t keep_with_variations (hb_collect_feature_substitutes_with_var_context_t *c,
2935 hb_map_t *condition_map /* OUT */) const
2936 {
2937 //invalid axis index, drop the entire record
2938 if (!c->axes_index_tag_map->has (key: axisIndex))
2939 return DROP_RECORD_WITH_VAR;
2940
2941 hb_tag_t axis_tag = c->axes_index_tag_map->get (key: axisIndex);
2942
2943 //axis not pinned, keep the condition
2944 if (!c->axes_location->has (key: axis_tag))
2945 {
2946 // add axisIndex->value into the hashmap so we can check if the record is
2947 // unique with variations
2948 int16_t min_val = filterRangeMinValue.to_int ();
2949 int16_t max_val = filterRangeMaxValue.to_int ();
2950 hb_codepoint_t val = (max_val << 16) + min_val;
2951
2952 condition_map->set (key: axisIndex, value&: val);
2953 return KEEP_COND_WITH_VAR;
2954 }
2955
2956 //axis pinned, check if condition is met
2957 //TODO: add check for axis Ranges
2958 int v = c->axes_location->get (key: axis_tag);
2959
2960 //condition not met, drop the entire record
2961 if (v < filterRangeMinValue.to_int () || v > filterRangeMaxValue.to_int ())
2962 return DROP_RECORD_WITH_VAR;
2963
2964 //axis pinned and condition met, drop the condition
2965 return DROP_COND_WITH_VAR;
2966 }
2967
2968 bool evaluate (const int *coords, unsigned int coord_len) const
2969 {
2970 int coord = axisIndex < coord_len ? coords[axisIndex] : 0;
2971 return filterRangeMinValue.to_int () <= coord && coord <= filterRangeMaxValue.to_int ();
2972 }
2973
2974 bool sanitize (hb_sanitize_context_t *c) const
2975 {
2976 TRACE_SANITIZE (this);
2977 return_trace (c->check_struct (this));
2978 }
2979
2980 protected:
2981 HBUINT16 format; /* Format identifier--format = 1 */
2982 HBUINT16 axisIndex;
2983 F2DOT14 filterRangeMinValue;
2984 F2DOT14 filterRangeMaxValue;
2985 public:
2986 DEFINE_SIZE_STATIC (8);
2987};
2988
2989struct Condition
2990{
2991 bool evaluate (const int *coords, unsigned int coord_len) const
2992 {
2993 switch (u.format) {
2994 case 1: return u.format1.evaluate (coords, coord_len);
2995 default:return false;
2996 }
2997 }
2998
2999 Cond_with_Var_flag_t keep_with_variations (hb_collect_feature_substitutes_with_var_context_t *c,
3000 hb_map_t *condition_map /* OUT */) const
3001 {
3002 switch (u.format) {
3003 case 1: return u.format1.keep_with_variations (c, condition_map);
3004 default:return KEEP_COND_WITH_VAR;
3005 }
3006 }
3007
3008 template <typename context_t, typename ...Ts>
3009 typename context_t::return_t dispatch (context_t *c, Ts&&... ds) const
3010 {
3011 if (unlikely (!c->may_dispatch (this, &u.format))) return c->no_dispatch_return_value ();
3012 TRACE_DISPATCH (this, u.format);
3013 switch (u.format) {
3014 case 1: return_trace (c->dispatch (u.format1, std::forward<Ts> (ds)...));
3015 default:return_trace (c->default_return_value ());
3016 }
3017 }
3018
3019 bool sanitize (hb_sanitize_context_t *c) const
3020 {
3021 TRACE_SANITIZE (this);
3022 if (!u.format.sanitize (c)) return_trace (false);
3023 switch (u.format) {
3024 case 1: return_trace (u.format1.sanitize (c));
3025 default:return_trace (true);
3026 }
3027 }
3028
3029 protected:
3030 union {
3031 HBUINT16 format; /* Format identifier */
3032 ConditionFormat1 format1;
3033 } u;
3034 public:
3035 DEFINE_SIZE_UNION (2, format);
3036};
3037
3038struct ConditionSet
3039{
3040 bool evaluate (const int *coords, unsigned int coord_len) const
3041 {
3042 unsigned int count = conditions.len;
3043 for (unsigned int i = 0; i < count; i++)
3044 if (!(this+conditions.arrayZ[i]).evaluate (coords, coord_len))
3045 return false;
3046 return true;
3047 }
3048
3049 Cond_with_Var_flag_t keep_with_variations (hb_collect_feature_substitutes_with_var_context_t *c) const
3050 {
3051 hb_map_t *condition_map = hb_map_create ();
3052 if (unlikely (!condition_map)) return MEM_ERR_WITH_VAR;
3053 hb::shared_ptr<hb_map_t> p {condition_map};
3054
3055 hb_set_t *cond_set = hb_set_create ();
3056 if (unlikely (!cond_set)) return MEM_ERR_WITH_VAR;
3057 hb::shared_ptr<hb_set_t> s {cond_set};
3058
3059 unsigned num_kept_cond = 0, cond_idx = 0;
3060 for (const auto& offset : conditions)
3061 {
3062 Cond_with_Var_flag_t ret = (this+offset).keep_with_variations (c, condition_map);
3063 // one condition is not met, drop the entire record
3064 if (ret == DROP_RECORD_WITH_VAR)
3065 return DROP_RECORD_WITH_VAR;
3066
3067 // axis not pinned, keep this condition
3068 if (ret == KEEP_COND_WITH_VAR)
3069 {
3070 cond_set->add (g: cond_idx);
3071 num_kept_cond++;
3072 }
3073 cond_idx++;
3074 }
3075
3076 // all conditions met
3077 if (num_kept_cond == 0) return DROP_COND_WITH_VAR;
3078
3079 //check if condition_set is unique with variations
3080 if (c->conditionset_map->has (key: p))
3081 //duplicate found, drop the entire record
3082 return DROP_RECORD_WITH_VAR;
3083
3084 c->conditionset_map->set (key: p, value: 1);
3085 c->record_cond_idx_map->set (key: c->cur_record_idx, value&: s);
3086
3087 return KEEP_COND_WITH_VAR;
3088 }
3089
3090 bool subset (hb_subset_context_t *c,
3091 hb_subset_layout_context_t *l) const
3092 {
3093 TRACE_SUBSET (this);
3094 auto *out = c->serializer->start_embed (obj: this);
3095 if (unlikely (!out || !c->serializer->extend_min (out))) return_trace (false);
3096
3097 hb_set_t *retained_cond_set = nullptr;
3098 if (l->feature_record_cond_idx_map != nullptr)
3099 retained_cond_set = l->feature_record_cond_idx_map->get (key: l->cur_feature_var_record_idx);
3100
3101 unsigned int count = conditions.len;
3102 for (unsigned int i = 0; i < count; i++)
3103 {
3104 if (retained_cond_set != nullptr && !retained_cond_set->has (k: i))
3105 continue;
3106 subset_offset_array (c, out->conditions, this) (conditions[i]);
3107 }
3108
3109 return_trace (bool (out->conditions));
3110 }
3111
3112 bool sanitize (hb_sanitize_context_t *c) const
3113 {
3114 TRACE_SANITIZE (this);
3115 return_trace (conditions.sanitize (c, this));
3116 }
3117
3118 protected:
3119 Array16OfOffset32To<Condition> conditions;
3120 public:
3121 DEFINE_SIZE_ARRAY (2, conditions);
3122};
3123
3124struct FeatureTableSubstitutionRecord
3125{
3126 friend struct FeatureTableSubstitution;
3127
3128 void collect_lookups (const void *base, hb_set_t *lookup_indexes /* OUT */) const
3129 {
3130 return (base+feature).add_lookup_indexes_to (lookup_indexes);
3131 }
3132
3133 void closure_features (const void *base,
3134 const hb_map_t *lookup_indexes,
3135 hb_set_t *feature_indexes /* OUT */) const
3136 {
3137 if ((base+feature).intersects_lookup_indexes (lookup_indexes))
3138 feature_indexes->add (g: featureIndex);
3139 }
3140
3141 void collect_feature_substitutes_with_variations (hb_hashmap_t<unsigned, const Feature*> *feature_substitutes_map,
3142 const hb_set_t *feature_indices,
3143 const void *base) const
3144 {
3145 if (feature_indices->has (k: featureIndex))
3146 feature_substitutes_map->set (key: featureIndex, value: &(base+feature));
3147 }
3148
3149 bool subset (hb_subset_layout_context_t *c, const void *base) const
3150 {
3151 TRACE_SUBSET (this);
3152 if (!c->feature_index_map->has (key: featureIndex) ||
3153 c->feature_substitutes_map->has (key: featureIndex)) {
3154 // Feature that is being substituted is not being retained, so we don't
3155 // need this.
3156 return_trace (false);
3157 }
3158
3159 auto *out = c->subset_context->serializer->embed (obj: this);
3160 if (unlikely (!out)) return_trace (false);
3161
3162 out->featureIndex = c->feature_index_map->get (key: featureIndex);
3163 bool ret = out->feature.serialize_subset (c: c->subset_context, src: feature, src_base: base, ds&: c);
3164 return_trace (ret);
3165 }
3166
3167 bool sanitize (hb_sanitize_context_t *c, const void *base) const
3168 {
3169 TRACE_SANITIZE (this);
3170 return_trace (c->check_struct (this) && feature.sanitize (c, base));
3171 }
3172
3173 protected:
3174 HBUINT16 featureIndex;
3175 Offset32To<Feature> feature;
3176 public:
3177 DEFINE_SIZE_STATIC (6);
3178};
3179
3180struct FeatureTableSubstitution
3181{
3182 const Feature *find_substitute (unsigned int feature_index) const
3183 {
3184 unsigned int count = substitutions.len;
3185 for (unsigned int i = 0; i < count; i++)
3186 {
3187 const FeatureTableSubstitutionRecord &record = substitutions.arrayZ[i];
3188 if (record.featureIndex == feature_index)
3189 return &(this+record.feature);
3190 }
3191 return nullptr;
3192 }
3193
3194 void collect_lookups (const hb_set_t *feature_indexes,
3195 const hb_hashmap_t<unsigned, const Feature*> *feature_substitutes_map,
3196 hb_set_t *lookup_indexes /* OUT */) const
3197 {
3198 + hb_iter (substitutions)
3199 | hb_filter (feature_indexes, &FeatureTableSubstitutionRecord::featureIndex)
3200 | hb_filter ([feature_substitutes_map] (const FeatureTableSubstitutionRecord& record)
3201 {
3202 if (feature_substitutes_map == nullptr) return true;
3203 return !feature_substitutes_map->has (key: record.featureIndex);
3204 })
3205 | hb_apply ([this, lookup_indexes] (const FeatureTableSubstitutionRecord& r)
3206 { r.collect_lookups (base: this, lookup_indexes); })
3207 ;
3208 }
3209
3210 void closure_features (const hb_map_t *lookup_indexes,
3211 hb_set_t *feature_indexes /* OUT */) const
3212 {
3213 for (const FeatureTableSubstitutionRecord& record : substitutions)
3214 record.closure_features (base: this, lookup_indexes, feature_indexes);
3215 }
3216
3217 bool intersects_features (const hb_map_t *feature_index_map) const
3218 {
3219 for (const FeatureTableSubstitutionRecord& record : substitutions)
3220 {
3221 if (feature_index_map->has (key: record.featureIndex)) return true;
3222 }
3223 return false;
3224 }
3225
3226 void collect_feature_substitutes_with_variations (hb_collect_feature_substitutes_with_var_context_t *c) const
3227 {
3228 for (const FeatureTableSubstitutionRecord& record : substitutions)
3229 record.collect_feature_substitutes_with_variations (feature_substitutes_map: c->feature_substitutes_map, feature_indices: c->feature_indices, base: this);
3230 }
3231
3232 bool subset (hb_subset_context_t *c,
3233 hb_subset_layout_context_t *l) const
3234 {
3235 TRACE_SUBSET (this);
3236 auto *out = c->serializer->start_embed (obj: *this);
3237 if (unlikely (!out || !c->serializer->extend_min (out))) return_trace (false);
3238
3239 out->version.major = version.major;
3240 out->version.minor = version.minor;
3241
3242 + substitutions.iter ()
3243 | hb_apply (subset_record_array (l, &(out->substitutions), this))
3244 ;
3245
3246 return_trace (bool (out->substitutions));
3247 }
3248
3249 bool sanitize (hb_sanitize_context_t *c) const
3250 {
3251 TRACE_SANITIZE (this);
3252 return_trace (version.sanitize (c) &&
3253 likely (version.major == 1) &&
3254 substitutions.sanitize (c, this));
3255 }
3256
3257 protected:
3258 FixedVersion<> version; /* Version--0x00010000u */
3259 Array16Of<FeatureTableSubstitutionRecord>
3260 substitutions;
3261 public:
3262 DEFINE_SIZE_ARRAY (6, substitutions);
3263};
3264
3265struct FeatureVariationRecord
3266{
3267 friend struct FeatureVariations;
3268
3269 void collect_lookups (const void *base,
3270 const hb_set_t *feature_indexes,
3271 const hb_hashmap_t<unsigned, const Feature*> *feature_substitutes_map,
3272 hb_set_t *lookup_indexes /* OUT */) const
3273 {
3274 return (base+substitutions).collect_lookups (feature_indexes, feature_substitutes_map, lookup_indexes);
3275 }
3276
3277 void closure_features (const void *base,
3278 const hb_map_t *lookup_indexes,
3279 hb_set_t *feature_indexes /* OUT */) const
3280 {
3281 (base+substitutions).closure_features (lookup_indexes, feature_indexes);
3282 }
3283
3284 bool intersects_features (const void *base, const hb_map_t *feature_index_map) const
3285 {
3286 return (base+substitutions).intersects_features (feature_index_map);
3287 }
3288
3289 void collect_feature_substitutes_with_variations (hb_collect_feature_substitutes_with_var_context_t *c,
3290 const void *base) const
3291 {
3292 // ret == 1, all conditions met
3293 if ((base+conditions).keep_with_variations (c) == DROP_COND_WITH_VAR &&
3294 c->apply)
3295 {
3296 (base+substitutions).collect_feature_substitutes_with_variations (c);
3297 c->apply = false; // set variations only once
3298 }
3299 }
3300
3301 bool subset (hb_subset_layout_context_t *c, const void *base) const
3302 {
3303 TRACE_SUBSET (this);
3304 auto *out = c->subset_context->serializer->embed (obj: this);
3305 if (unlikely (!out)) return_trace (false);
3306
3307 out->conditions.serialize_subset (c: c->subset_context, src: conditions, src_base: base, ds&: c);
3308 out->substitutions.serialize_subset (c: c->subset_context, src: substitutions, src_base: base, ds&: c);
3309
3310 return_trace (true);
3311 }
3312
3313 bool sanitize (hb_sanitize_context_t *c, const void *base) const
3314 {
3315 TRACE_SANITIZE (this);
3316 return_trace (conditions.sanitize (c, base) &&
3317 substitutions.sanitize (c, base));
3318 }
3319
3320 protected:
3321 Offset32To<ConditionSet>
3322 conditions;
3323 Offset32To<FeatureTableSubstitution>
3324 substitutions;
3325 public:
3326 DEFINE_SIZE_STATIC (8);
3327};
3328
3329struct FeatureVariations
3330{
3331 static constexpr unsigned NOT_FOUND_INDEX = 0xFFFFFFFFu;
3332
3333 bool find_index (const int *coords, unsigned int coord_len,
3334 unsigned int *index) const
3335 {
3336 unsigned int count = varRecords.len;
3337 for (unsigned int i = 0; i < count; i++)
3338 {
3339 const FeatureVariationRecord &record = varRecords.arrayZ[i];
3340 if ((this+record.conditions).evaluate (coords, coord_len))
3341 {
3342 *index = i;
3343 return true;
3344 }
3345 }
3346 *index = NOT_FOUND_INDEX;
3347 return false;
3348 }
3349
3350 const Feature *find_substitute (unsigned int variations_index,
3351 unsigned int feature_index) const
3352 {
3353 const FeatureVariationRecord &record = varRecords[variations_index];
3354 return (this+record.substitutions).find_substitute (feature_index);
3355 }
3356
3357 void collect_feature_substitutes_with_variations (hb_collect_feature_substitutes_with_var_context_t *c) const
3358 {
3359 unsigned int count = varRecords.len;
3360 for (unsigned int i = 0; i < count; i++)
3361 {
3362 c->cur_record_idx = i;
3363 varRecords[i].collect_feature_substitutes_with_variations (c, base: this);
3364 }
3365 }
3366
3367 FeatureVariations* copy (hb_serialize_context_t *c) const
3368 {
3369 TRACE_SERIALIZE (this);
3370 return_trace (c->embed (*this));
3371 }
3372
3373 void collect_lookups (const hb_set_t *feature_indexes,
3374 const hb_hashmap_t<unsigned, const Feature*> *feature_substitutes_map,
3375 hb_set_t *lookup_indexes /* OUT */) const
3376 {
3377 for (const FeatureVariationRecord& r : varRecords)
3378 r.collect_lookups (base: this, feature_indexes, feature_substitutes_map, lookup_indexes);
3379 }
3380
3381 void closure_features (const hb_map_t *lookup_indexes,
3382 const hb_hashmap_t<unsigned, hb::shared_ptr<hb_set_t>> *feature_record_cond_idx_map,
3383 hb_set_t *feature_indexes /* OUT */) const
3384 {
3385 unsigned int count = varRecords.len;
3386 for (unsigned int i = 0; i < count; i++)
3387 {
3388 if (feature_record_cond_idx_map != nullptr &&
3389 !feature_record_cond_idx_map->has (key: i))
3390 continue;
3391 varRecords[i].closure_features (base: this, lookup_indexes, feature_indexes);
3392 }
3393 }
3394
3395 bool subset (hb_subset_context_t *c,
3396 hb_subset_layout_context_t *l) const
3397 {
3398 TRACE_SUBSET (this);
3399 auto *out = c->serializer->start_embed (obj: *this);
3400 if (unlikely (!out || !c->serializer->extend_min (out))) return_trace (false);
3401
3402 out->version.major = version.major;
3403 out->version.minor = version.minor;
3404
3405 int keep_up_to = -1;
3406 for (int i = varRecords.len - 1; i >= 0; i--) {
3407 if (varRecords[i].intersects_features (base: this, feature_index_map: l->feature_index_map)) {
3408 keep_up_to = i;
3409 break;
3410 }
3411 }
3412
3413 unsigned count = (unsigned) (keep_up_to + 1);
3414 for (unsigned i = 0; i < count; i++)
3415 {
3416 if (l->feature_record_cond_idx_map != nullptr &&
3417 !l->feature_record_cond_idx_map->has (key: i))
3418 continue;
3419
3420 l->cur_feature_var_record_idx = i;
3421 subset_record_array (l, &(out->varRecords), this) (varRecords[i]);
3422 }
3423 return_trace (bool (out->varRecords));
3424 }
3425
3426 bool sanitize (hb_sanitize_context_t *c) const
3427 {
3428 TRACE_SANITIZE (this);
3429 return_trace (version.sanitize (c) &&
3430 likely (version.major == 1) &&
3431 varRecords.sanitize (c, this));
3432 }
3433
3434 protected:
3435 FixedVersion<> version; /* Version--0x00010000u */
3436 Array32Of<FeatureVariationRecord>
3437 varRecords;
3438 public:
3439 DEFINE_SIZE_ARRAY_SIZED (8, varRecords);
3440};
3441
3442
3443/*
3444 * Device Tables
3445 */
3446
3447struct HintingDevice
3448{
3449 friend struct Device;
3450
3451 private:
3452
3453 hb_position_t get_x_delta (hb_font_t *font) const
3454 { return get_delta (ppem: font->x_ppem, scale: font->x_scale); }
3455
3456 hb_position_t get_y_delta (hb_font_t *font) const
3457 { return get_delta (ppem: font->y_ppem, scale: font->y_scale); }
3458
3459 public:
3460
3461 unsigned int get_size () const
3462 {
3463 unsigned int f = deltaFormat;
3464 if (unlikely (f < 1 || f > 3 || startSize > endSize)) return 3 * HBUINT16::static_size;
3465 return HBUINT16::static_size * (4 + ((endSize - startSize) >> (4 - f)));
3466 }
3467
3468 bool sanitize (hb_sanitize_context_t *c) const
3469 {
3470 TRACE_SANITIZE (this);
3471 return_trace (c->check_struct (this) && c->check_range (this, this->get_size ()));
3472 }
3473
3474 HintingDevice* copy (hb_serialize_context_t *c) const
3475 {
3476 TRACE_SERIALIZE (this);
3477 return_trace (c->embed<HintingDevice> (this));
3478 }
3479
3480 private:
3481
3482 int get_delta (unsigned int ppem, int scale) const
3483 {
3484 if (!ppem) return 0;
3485
3486 int pixels = get_delta_pixels (ppem_size: ppem);
3487
3488 if (!pixels) return 0;
3489
3490 return (int) (pixels * (int64_t) scale / ppem);
3491 }
3492 int get_delta_pixels (unsigned int ppem_size) const
3493 {
3494 unsigned int f = deltaFormat;
3495 if (unlikely (f < 1 || f > 3))
3496 return 0;
3497
3498 if (ppem_size < startSize || ppem_size > endSize)
3499 return 0;
3500
3501 unsigned int s = ppem_size - startSize;
3502
3503 unsigned int byte = deltaValueZ[s >> (4 - f)];
3504 unsigned int bits = (byte >> (16 - (((s & ((1 << (4 - f)) - 1)) + 1) << f)));
3505 unsigned int mask = (0xFFFFu >> (16 - (1 << f)));
3506
3507 int delta = bits & mask;
3508
3509 if ((unsigned int) delta >= ((mask + 1) >> 1))
3510 delta -= mask + 1;
3511
3512 return delta;
3513 }
3514
3515 protected:
3516 HBUINT16 startSize; /* Smallest size to correct--in ppem */
3517 HBUINT16 endSize; /* Largest size to correct--in ppem */
3518 HBUINT16 deltaFormat; /* Format of DeltaValue array data: 1, 2, or 3
3519 * 1 Signed 2-bit value, 8 values per uint16
3520 * 2 Signed 4-bit value, 4 values per uint16
3521 * 3 Signed 8-bit value, 2 values per uint16
3522 */
3523 UnsizedArrayOf<HBUINT16>
3524 deltaValueZ; /* Array of compressed data */
3525 public:
3526 DEFINE_SIZE_ARRAY (6, deltaValueZ);
3527};
3528
3529struct VariationDevice
3530{
3531 friend struct Device;
3532
3533 private:
3534
3535 hb_position_t get_x_delta (hb_font_t *font,
3536 const VariationStore &store,
3537 VariationStore::cache_t *store_cache = nullptr) const
3538 { return font->em_scalef_x (v: get_delta (font, store, store_cache)); }
3539
3540 hb_position_t get_y_delta (hb_font_t *font,
3541 const VariationStore &store,
3542 VariationStore::cache_t *store_cache = nullptr) const
3543 { return font->em_scalef_y (v: get_delta (font, store, store_cache)); }
3544
3545 VariationDevice* copy (hb_serialize_context_t *c,
3546 const hb_hashmap_t<unsigned, hb_pair_t<unsigned, int>> *layout_variation_idx_delta_map) const
3547 {
3548 TRACE_SERIALIZE (this);
3549 if (!layout_variation_idx_delta_map) return_trace (nullptr);
3550
3551 hb_pair_t<unsigned, int> *v;
3552 if (!layout_variation_idx_delta_map->has (key: varIdx, vp: &v))
3553 return_trace (nullptr);
3554
3555 c->start_zerocopy (size: this->static_size);
3556 auto *out = c->embed (obj: this);
3557 if (unlikely (!out)) return_trace (nullptr);
3558
3559 unsigned new_idx = hb_first (*v);
3560 out->varIdx = new_idx;
3561 return_trace (out);
3562 }
3563
3564 void collect_variation_index (hb_collect_variation_indices_context_t *c) const
3565 {
3566 c->layout_variation_indices->add (g: varIdx);
3567 int delta = 0;
3568 if (c->normalized_coords && c->var_store)
3569 delta = roundf (c->var_store->get_delta (varIdx, c->normalized_coords->arrayZ,
3570 c->normalized_coords->length, c->store_cache));
3571
3572 /* set new varidx to HB_OT_LAYOUT_NO_VARIATIONS_INDEX here, will remap
3573 * varidx later*/
3574 c->varidx_delta_map->set (key: varIdx, value: hb_pair_t<unsigned, int> (HB_OT_LAYOUT_NO_VARIATIONS_INDEX, delta));
3575 }
3576
3577 bool sanitize (hb_sanitize_context_t *c) const
3578 {
3579 TRACE_SANITIZE (this);
3580 return_trace (c->check_struct (this));
3581 }
3582
3583 private:
3584
3585 float get_delta (hb_font_t *font,
3586 const VariationStore &store,
3587 VariationStore::cache_t *store_cache = nullptr) const
3588 {
3589 return store.get_delta (index: varIdx, coords: font->coords, coord_count: font->num_coords, cache: (VariationStore::cache_t *) store_cache);
3590 }
3591
3592 protected:
3593 VarIdx varIdx;
3594 HBUINT16 deltaFormat; /* Format identifier for this table: 0x0x8000 */
3595 public:
3596 DEFINE_SIZE_STATIC (6);
3597};
3598
3599struct DeviceHeader
3600{
3601 protected:
3602 HBUINT16 reserved1;
3603 HBUINT16 reserved2;
3604 public:
3605 HBUINT16 format; /* Format identifier */
3606 public:
3607 DEFINE_SIZE_STATIC (6);
3608};
3609
3610struct Device
3611{
3612 hb_position_t get_x_delta (hb_font_t *font,
3613 const VariationStore &store=Null (VariationStore),
3614 VariationStore::cache_t *store_cache = nullptr) const
3615 {
3616 switch (u.b.format)
3617 {
3618#ifndef HB_NO_HINTING
3619 case 1: case 2: case 3:
3620 return u.hinting.get_x_delta (font);
3621#endif
3622#ifndef HB_NO_VAR
3623 case 0x8000:
3624 return u.variation.get_x_delta (font, store, store_cache);
3625#endif
3626 default:
3627 return 0;
3628 }
3629 }
3630 hb_position_t get_y_delta (hb_font_t *font,
3631 const VariationStore &store=Null (VariationStore),
3632 VariationStore::cache_t *store_cache = nullptr) const
3633 {
3634 switch (u.b.format)
3635 {
3636 case 1: case 2: case 3:
3637#ifndef HB_NO_HINTING
3638 return u.hinting.get_y_delta (font);
3639#endif
3640#ifndef HB_NO_VAR
3641 case 0x8000:
3642 return u.variation.get_y_delta (font, store, store_cache);
3643#endif
3644 default:
3645 return 0;
3646 }
3647 }
3648
3649 bool sanitize (hb_sanitize_context_t *c) const
3650 {
3651 TRACE_SANITIZE (this);
3652 if (!u.b.format.sanitize (c)) return_trace (false);
3653 switch (u.b.format) {
3654#ifndef HB_NO_HINTING
3655 case 1: case 2: case 3:
3656 return_trace (u.hinting.sanitize (c));
3657#endif
3658#ifndef HB_NO_VAR
3659 case 0x8000:
3660 return_trace (u.variation.sanitize (c));
3661#endif
3662 default:
3663 return_trace (true);
3664 }
3665 }
3666
3667 Device* copy (hb_serialize_context_t *c,
3668 const hb_hashmap_t<unsigned, hb_pair_t<unsigned, int>> *layout_variation_idx_delta_map=nullptr) const
3669 {
3670 TRACE_SERIALIZE (this);
3671 switch (u.b.format) {
3672#ifndef HB_NO_HINTING
3673 case 1:
3674 case 2:
3675 case 3:
3676 return_trace (reinterpret_cast<Device *> (u.hinting.copy (c)));
3677#endif
3678#ifndef HB_NO_VAR
3679 case 0x8000:
3680 return_trace (reinterpret_cast<Device *> (u.variation.copy (c, layout_variation_idx_delta_map)));
3681#endif
3682 default:
3683 return_trace (nullptr);
3684 }
3685 }
3686
3687 void collect_variation_indices (hb_collect_variation_indices_context_t *c) const
3688 {
3689 switch (u.b.format) {
3690#ifndef HB_NO_HINTING
3691 case 1:
3692 case 2:
3693 case 3:
3694 return;
3695#endif
3696#ifndef HB_NO_VAR
3697 case 0x8000:
3698 u.variation.collect_variation_index (c);
3699 return;
3700#endif
3701 default:
3702 return;
3703 }
3704 }
3705
3706 unsigned get_variation_index () const
3707 {
3708 switch (u.b.format) {
3709#ifndef HB_NO_VAR
3710 case 0x8000:
3711 return u.variation.varIdx;
3712#endif
3713 default:
3714 return HB_OT_LAYOUT_NO_VARIATIONS_INDEX;
3715 }
3716 }
3717
3718 protected:
3719 union {
3720 DeviceHeader b;
3721 HintingDevice hinting;
3722#ifndef HB_NO_VAR
3723 VariationDevice variation;
3724#endif
3725 } u;
3726 public:
3727 DEFINE_SIZE_UNION (6, b);
3728};
3729
3730
3731} /* namespace OT */
3732
3733
3734#endif /* HB_OT_LAYOUT_COMMON_HH */
3735

source code of flutter_engine/third_party/harfbuzz/src/hb-ot-layout-common.hh