Imported Upstream version 8.2.2
[platform/upstream/harfbuzz.git] / src / OT / Color / CBDT / CBDT.hh
1 /*
2  * Copyright © 2016  Google, Inc.
3  *
4  *  This is part of HarfBuzz, a text shaping library.
5  *
6  * Permission is hereby granted, without written agreement and without
7  * license or royalty fees, to use, copy, modify, and distribute this
8  * software and its documentation for any purpose, provided that the
9  * above copyright notice and the following two paragraphs appear in
10  * all copies of this software.
11  *
12  * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
13  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
14  * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
15  * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
16  * DAMAGE.
17  *
18  * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
19  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20  * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
21  * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
22  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
23  *
24  * Google Author(s): Seigo Nonaka, Calder Kitagawa
25  */
26
27 #ifndef OT_COLOR_CBDT_CBDT_HH
28 #define OT_COLOR_CBDT_CBDT_HH
29
30 #include "../../../hb-open-type.hh"
31 #include "../../../hb-paint.hh"
32
33 /*
34  * CBLC -- Color Bitmap Location
35  * https://docs.microsoft.com/en-us/typography/opentype/spec/cblc
36  * https://docs.microsoft.com/en-us/typography/opentype/spec/eblc
37  * CBDT -- Color Bitmap Data
38  * https://docs.microsoft.com/en-us/typography/opentype/spec/cbdt
39  * https://docs.microsoft.com/en-us/typography/opentype/spec/ebdt
40  */
41 #define HB_OT_TAG_CBLC HB_TAG('C','B','L','C')
42 #define HB_OT_TAG_CBDT HB_TAG('C','B','D','T')
43
44
45 namespace OT {
46
47 struct cblc_bitmap_size_subset_context_t
48 {
49   const char *cbdt;
50   unsigned int cbdt_length;
51   hb_vector_t<char> *cbdt_prime;
52   unsigned int size;            /* INOUT
53                                  *  Input: old size of IndexSubtable
54                                  *  Output: new size of IndexSubtable
55                                  */
56   unsigned int num_tables;      /* INOUT
57                                  *  Input: old number of subtables.
58                                  *  Output: new number of subtables.
59                                  */
60   hb_codepoint_t start_glyph;   /* OUT */
61   hb_codepoint_t end_glyph;     /* OUT */
62 };
63
64 static inline bool
65 _copy_data_to_cbdt (hb_vector_t<char> *cbdt_prime,
66                     const void        *data,
67                     unsigned           length)
68 {
69   unsigned int new_len = cbdt_prime->length + length;
70   if (unlikely (!cbdt_prime->alloc (new_len))) return false;
71   hb_memcpy (cbdt_prime->arrayZ + cbdt_prime->length, data, length);
72   cbdt_prime->length = new_len;
73   return true;
74 }
75
76 struct SmallGlyphMetrics
77 {
78   bool sanitize (hb_sanitize_context_t *c) const
79   {
80     TRACE_SANITIZE (this);
81     return_trace (c->check_struct (this));
82   }
83
84   void get_extents (hb_font_t *font, hb_glyph_extents_t *extents, bool scale) const
85   {
86     extents->x_bearing = bearingX;
87     extents->y_bearing = bearingY;
88     extents->width = width;
89     extents->height = -static_cast<int> (height);
90
91     if (scale)
92       font->scale_glyph_extents (extents);
93   }
94
95   HBUINT8       height;
96   HBUINT8       width;
97   HBINT8        bearingX;
98   HBINT8        bearingY;
99   HBUINT8       advance;
100   public:
101   DEFINE_SIZE_STATIC (5);
102 };
103
104 struct BigGlyphMetrics : SmallGlyphMetrics
105 {
106   HBINT8        vertBearingX;
107   HBINT8        vertBearingY;
108   HBUINT8       vertAdvance;
109   public:
110   DEFINE_SIZE_STATIC (8);
111 };
112
113 struct SBitLineMetrics
114 {
115   bool sanitize (hb_sanitize_context_t *c) const
116   {
117     TRACE_SANITIZE (this);
118     return_trace (c->check_struct (this));
119   }
120
121   HBINT8        ascender;
122   HBINT8        decender;
123   HBUINT8       widthMax;
124   HBINT8        caretSlopeNumerator;
125   HBINT8        caretSlopeDenominator;
126   HBINT8        caretOffset;
127   HBINT8        minOriginSB;
128   HBINT8        minAdvanceSB;
129   HBINT8        maxBeforeBL;
130   HBINT8        minAfterBL;
131   HBINT8        padding1;
132   HBINT8        padding2;
133   public:
134   DEFINE_SIZE_STATIC (12);
135 };
136
137
138 /*
139  * Index Subtables.
140  */
141
142 struct IndexSubtableHeader
143 {
144   bool sanitize (hb_sanitize_context_t *c) const
145   {
146     TRACE_SANITIZE (this);
147     return_trace (c->check_struct (this));
148   }
149
150   HBUINT16      indexFormat;
151   HBUINT16      imageFormat;
152   HBUINT32      imageDataOffset;
153   public:
154   DEFINE_SIZE_STATIC (8);
155 };
156
157 template <typename OffsetType>
158 struct IndexSubtableFormat1Or3
159 {
160   bool sanitize (hb_sanitize_context_t *c, unsigned int glyph_count) const
161   {
162     TRACE_SANITIZE (this);
163     return_trace (c->check_struct (this) &&
164                   offsetArrayZ.sanitize (c, glyph_count + 1));
165   }
166
167   bool get_image_data (unsigned int idx,
168                        unsigned int *offset,
169                        unsigned int *length) const
170   {
171     if (unlikely (offsetArrayZ[idx + 1] <= offsetArrayZ[idx]))
172       return false;
173
174     *offset = header.imageDataOffset + offsetArrayZ[idx];
175     *length = offsetArrayZ[idx + 1] - offsetArrayZ[idx];
176     return true;
177   }
178
179   bool add_offset (hb_serialize_context_t *c,
180                    unsigned int offset,
181                    unsigned int *size /* OUT (accumulated) */)
182   {
183     TRACE_SERIALIZE (this);
184     Offset<OffsetType> embedded_offset;
185     embedded_offset = offset;
186     *size += sizeof (OffsetType);
187     auto *o = c->embed (embedded_offset);
188     return_trace ((bool) o);
189   }
190
191   IndexSubtableHeader   header;
192   UnsizedArrayOf<Offset<OffsetType>>
193                         offsetArrayZ;
194   public:
195   DEFINE_SIZE_ARRAY (8, offsetArrayZ);
196 };
197
198 struct IndexSubtableFormat1 : IndexSubtableFormat1Or3<HBUINT32> {};
199 struct IndexSubtableFormat3 : IndexSubtableFormat1Or3<HBUINT16> {};
200
201 struct IndexSubtable
202 {
203   bool sanitize (hb_sanitize_context_t *c, unsigned int glyph_count) const
204   {
205     TRACE_SANITIZE (this);
206     if (!u.header.sanitize (c)) return_trace (false);
207     switch (u.header.indexFormat)
208     {
209     case 1: return_trace (u.format1.sanitize (c, glyph_count));
210     case 3: return_trace (u.format3.sanitize (c, glyph_count));
211     default:return_trace (true);
212     }
213   }
214
215   bool
216   finish_subtable (hb_serialize_context_t *c,
217                    unsigned int cbdt_prime_len,
218                    unsigned int num_glyphs,
219                    unsigned int *size /* OUT (accumulated) */)
220   {
221     TRACE_SERIALIZE (this);
222
223     unsigned int local_offset = cbdt_prime_len - u.header.imageDataOffset;
224     switch (u.header.indexFormat)
225     {
226     case 1: return_trace (u.format1.add_offset (c, local_offset, size));
227     case 3: {
228       if (!u.format3.add_offset (c, local_offset, size))
229         return_trace (false);
230       if (!(num_glyphs & 0x01))  // Pad to 32-bit alignment if needed.
231         return_trace (u.format3.add_offset (c, 0, size));
232       return_trace (true);
233     }
234     // TODO: implement 2, 4, 5.
235     case 2: case 4:  // No-op.
236     case 5:  // Pad to 32-bit aligned.
237     default: return_trace (false);
238     }
239   }
240
241   bool
242   fill_missing_glyphs (hb_serialize_context_t *c,
243                        unsigned int cbdt_prime_len,
244                        unsigned int num_missing,
245                        unsigned int *size /* OUT (accumulated) */,
246                        unsigned int *num_glyphs /* OUT (accumulated) */)
247   {
248     TRACE_SERIALIZE (this);
249
250     unsigned int local_offset = cbdt_prime_len - u.header.imageDataOffset;
251     switch (u.header.indexFormat)
252     {
253     case 1: {
254       for (unsigned int i = 0; i < num_missing; i++)
255       {
256         if (unlikely (!u.format1.add_offset (c, local_offset, size)))
257           return_trace (false);
258         *num_glyphs += 1;
259       }
260       return_trace (true);
261     }
262     case 3: {
263       for (unsigned int i = 0; i < num_missing; i++)
264       {
265         if (unlikely (!u.format3.add_offset (c, local_offset, size)))
266           return_trace (false);
267         *num_glyphs += 1;
268       }
269       return_trace (true);
270     }
271     // TODO: implement 2, 4, 5.
272     case 2:  // Add empty space in cbdt_prime?.
273     case 4: case 5:  // No-op as sparse is supported.
274     default: return_trace (false);
275     }
276   }
277
278   bool
279   copy_glyph_at_idx (hb_serialize_context_t *c, unsigned int idx,
280                      const char *cbdt, unsigned int cbdt_length,
281                      hb_vector_t<char> *cbdt_prime /* INOUT */,
282                      IndexSubtable *subtable_prime /* INOUT */,
283                      unsigned int *size /* OUT (accumulated) */) const
284   {
285     TRACE_SERIALIZE (this);
286
287     unsigned int offset, length, format;
288     if (unlikely (!get_image_data (idx, &offset, &length, &format))) return_trace (false);
289     if (unlikely (offset > cbdt_length || cbdt_length - offset < length)) return_trace (false);
290
291     auto *header_prime = subtable_prime->get_header ();
292     unsigned int new_local_offset = cbdt_prime->length - (unsigned int) header_prime->imageDataOffset;
293     if (unlikely (!_copy_data_to_cbdt (cbdt_prime, cbdt + offset, length))) return_trace (false);
294
295     return_trace (subtable_prime->add_offset (c, new_local_offset, size));
296   }
297
298   bool
299   add_offset (hb_serialize_context_t *c, unsigned int local_offset,
300               unsigned int *size /* OUT (accumulated) */)
301   {
302     TRACE_SERIALIZE (this);
303     switch (u.header.indexFormat)
304     {
305     case 1: return_trace (u.format1.add_offset (c, local_offset, size));
306     case 3: return_trace (u.format3.add_offset (c, local_offset, size));
307     // TODO: Implement tables 2, 4, 5
308     case 2:  // Should be a no-op.
309     case 4: case 5:  // Handle sparse cases.
310     default: return_trace (false);
311     }
312   }
313
314   bool get_extents (hb_glyph_extents_t *extents HB_UNUSED, bool scale HB_UNUSED) const
315   {
316     switch (u.header.indexFormat)
317     {
318     case 2: case 5: /* TODO */
319     case 1: case 3: case 4: /* Variable-metrics formats do not have metrics here. */
320     default:return (false);
321     }
322   }
323
324   bool
325   get_image_data (unsigned int idx, unsigned int *offset,
326                   unsigned int *length, unsigned int *format) const
327   {
328     *format = u.header.imageFormat;
329     switch (u.header.indexFormat)
330     {
331     case 1: return u.format1.get_image_data (idx, offset, length);
332     case 3: return u.format3.get_image_data (idx, offset, length);
333     default: return false;
334     }
335   }
336
337   const IndexSubtableHeader* get_header () const { return &u.header; }
338
339   void populate_header (unsigned index_format,
340                         unsigned image_format,
341                         unsigned int image_data_offset,
342                         unsigned int *size)
343   {
344     u.header.indexFormat = index_format;
345     u.header.imageFormat = image_format;
346     u.header.imageDataOffset = image_data_offset;
347     switch (u.header.indexFormat)
348     {
349     case 1: *size += IndexSubtableFormat1::min_size; break;
350     case 3: *size += IndexSubtableFormat3::min_size; break;
351     }
352   }
353
354   protected:
355   union {
356   IndexSubtableHeader   header;
357   IndexSubtableFormat1  format1;
358   IndexSubtableFormat3  format3;
359   /* TODO: Format 2, 4, 5. */
360   } u;
361   public:
362   DEFINE_SIZE_UNION (8, header);
363 };
364
365 struct IndexSubtableRecord
366 {
367   /* XXX Remove this and fix by not inserting it into vector. */
368   IndexSubtableRecord& operator = (const IndexSubtableRecord &o)
369   {
370     firstGlyphIndex = o.firstGlyphIndex;
371     lastGlyphIndex = o.lastGlyphIndex;
372     offsetToSubtable = (unsigned) o.offsetToSubtable;
373     assert (offsetToSubtable.is_null ());
374     return *this;
375   }
376
377   bool sanitize (hb_sanitize_context_t *c, const void *base) const
378   {
379     TRACE_SANITIZE (this);
380     return_trace (c->check_struct (this) &&
381                   firstGlyphIndex <= lastGlyphIndex &&
382                   offsetToSubtable.sanitize (c, base, lastGlyphIndex - firstGlyphIndex + 1));
383   }
384
385   const IndexSubtable* get_subtable (const void *base) const
386   {
387     return &(base+offsetToSubtable);
388   }
389
390   bool add_new_subtable (hb_subset_context_t* c,
391                          cblc_bitmap_size_subset_context_t *bitmap_size_context,
392                          IndexSubtableRecord *record,
393                          const hb_vector_t<hb_pair_t<hb_codepoint_t, const IndexSubtableRecord*>> *lookup, /* IN */
394                          const void *base,
395                          unsigned int *start /* INOUT */) const
396   {
397     TRACE_SERIALIZE (this);
398
399     auto *subtable = c->serializer->start_embed<IndexSubtable> ();
400     if (unlikely (!c->serializer->extend_min (subtable))) return_trace (false);
401
402     auto *old_subtable = get_subtable (base);
403     auto *old_header = old_subtable->get_header ();
404
405     subtable->populate_header (old_header->indexFormat,
406                                old_header->imageFormat,
407                                bitmap_size_context->cbdt_prime->length,
408                                &bitmap_size_context->size);
409
410     unsigned int num_glyphs = 0;
411     bool early_exit = false;
412     for (unsigned int i = *start; i < lookup->length; i++)
413     {
414       hb_codepoint_t new_gid = (*lookup)[i].first;
415       const IndexSubtableRecord *next_record = (*lookup)[i].second;
416       const IndexSubtable *next_subtable = next_record->get_subtable (base);
417       auto *next_header = next_subtable->get_header ();
418       if (next_header != old_header)
419       {
420         *start = i;
421         early_exit = true;
422         break;
423       }
424       unsigned int num_missing = record->add_glyph_for_subset (new_gid);
425       if (unlikely (!subtable->fill_missing_glyphs (c->serializer,
426                                                     bitmap_size_context->cbdt_prime->length,
427                                                     num_missing,
428                                                     &bitmap_size_context->size,
429                                                     &num_glyphs)))
430         return_trace (false);
431
432       hb_codepoint_t old_gid = 0;
433       c->plan->old_gid_for_new_gid (new_gid, &old_gid);
434       if (old_gid < next_record->firstGlyphIndex)
435         return_trace (false);
436
437       unsigned int old_idx = (unsigned int) old_gid - next_record->firstGlyphIndex;
438       if (unlikely (!next_subtable->copy_glyph_at_idx (c->serializer,
439                                                        old_idx,
440                                                        bitmap_size_context->cbdt,
441                                                        bitmap_size_context->cbdt_length,
442                                                        bitmap_size_context->cbdt_prime,
443                                                        subtable,
444                                                        &bitmap_size_context->size)))
445         return_trace (false);
446       num_glyphs += 1;
447     }
448     if (!early_exit)
449       *start = lookup->length;
450     if (unlikely (!subtable->finish_subtable (c->serializer,
451                                               bitmap_size_context->cbdt_prime->length,
452                                               num_glyphs,
453                                               &bitmap_size_context->size)))
454       return_trace (false);
455     return_trace (true);
456   }
457
458   bool add_new_record (hb_subset_context_t *c,
459                        cblc_bitmap_size_subset_context_t *bitmap_size_context,
460                        const hb_vector_t<hb_pair_t<hb_codepoint_t, const IndexSubtableRecord*>> *lookup, /* IN */
461                        const void *base,
462                        unsigned int *start, /* INOUT */
463                        hb_vector_t<IndexSubtableRecord>* records /* INOUT */) const
464   {
465     TRACE_SERIALIZE (this);
466     auto snap = c->serializer->snapshot ();
467     unsigned int old_size = bitmap_size_context->size;
468     unsigned int old_cbdt_prime_length = bitmap_size_context->cbdt_prime->length;
469
470     // Set to invalid state to indicate filling glyphs is not yet started.
471     if (unlikely (!c->serializer->check_success (records->resize (records->length + 1))))
472       return_trace (false);
473
474     records->tail ().firstGlyphIndex = 1;
475     records->tail ().lastGlyphIndex = 0;
476     bitmap_size_context->size += IndexSubtableRecord::min_size;
477
478     c->serializer->push ();
479
480     if (unlikely (!add_new_subtable (c, bitmap_size_context, &(records->tail ()), lookup, base, start)))
481     {
482       c->serializer->pop_discard ();
483       c->serializer->revert (snap);
484       bitmap_size_context->cbdt_prime->shrink (old_cbdt_prime_length);
485       bitmap_size_context->size = old_size;
486       records->resize (records->length - 1);
487       return_trace (false);
488     }
489
490     bitmap_size_context->num_tables += 1;
491     return_trace (true);
492   }
493
494   unsigned int add_glyph_for_subset (hb_codepoint_t gid)
495   {
496     if (firstGlyphIndex > lastGlyphIndex)
497     {
498       firstGlyphIndex = gid;
499       lastGlyphIndex = gid;
500       return 0;
501     }
502     // TODO maybe assert? this shouldn't occur.
503     if (lastGlyphIndex > gid)
504       return 0;
505     unsigned int num_missing = (unsigned int) (gid - lastGlyphIndex - 1);
506     lastGlyphIndex = gid;
507     return num_missing;
508   }
509
510   bool get_extents (hb_glyph_extents_t *extents, const void *base, bool scale) const
511   { return (base+offsetToSubtable).get_extents (extents, scale); }
512
513   bool get_image_data (unsigned int  gid,
514                        const void   *base,
515                        unsigned int *offset,
516                        unsigned int *length,
517                        unsigned int *format) const
518   {
519     if (gid < firstGlyphIndex || gid > lastGlyphIndex) return false;
520     return (base+offsetToSubtable).get_image_data (gid - firstGlyphIndex,
521                                                    offset, length, format);
522   }
523
524   HBGlyphID16                   firstGlyphIndex;
525   HBGlyphID16                   lastGlyphIndex;
526   Offset32To<IndexSubtable>     offsetToSubtable;
527   public:
528   DEFINE_SIZE_STATIC (8);
529 };
530
531 struct IndexSubtableArray
532 {
533   friend struct CBDT;
534
535   bool sanitize (hb_sanitize_context_t *c, unsigned int count) const
536   {
537     TRACE_SANITIZE (this);
538     return_trace (indexSubtablesZ.sanitize (c, count, this));
539   }
540
541   void
542   build_lookup (hb_subset_context_t *c, cblc_bitmap_size_subset_context_t *bitmap_size_context,
543                 hb_vector_t<hb_pair_t<hb_codepoint_t,
544                 const IndexSubtableRecord*>> *lookup /* OUT */) const
545   {
546     bool start_glyph_is_set = false;
547     unsigned num_glyphs = c->plan->num_output_glyphs ();
548     for (hb_codepoint_t new_gid = 0; new_gid < num_glyphs; new_gid++)
549     {
550       hb_codepoint_t old_gid;
551       if (unlikely (!c->plan->old_gid_for_new_gid (new_gid, &old_gid))) continue;
552
553       const IndexSubtableRecord* record = find_table (old_gid, bitmap_size_context->num_tables);
554       if (unlikely (!record)) continue;
555
556       // Don't add gaps to the lookup. The best way to determine if a glyph is a
557       // gap is that it has no image data.
558       unsigned int offset, length, format;
559       if (unlikely (!record->get_image_data (old_gid, this, &offset, &length, &format))) continue;
560
561       lookup->push (hb_pair_t<hb_codepoint_t, const IndexSubtableRecord*> (new_gid, record));
562
563       if (!start_glyph_is_set)
564       {
565         bitmap_size_context->start_glyph = new_gid;
566         start_glyph_is_set = true;
567       }
568
569       bitmap_size_context->end_glyph = new_gid;
570     }
571   }
572
573   bool
574   subset (hb_subset_context_t *c,
575           cblc_bitmap_size_subset_context_t *bitmap_size_context) const
576   {
577     TRACE_SUBSET (this);
578
579     hb_vector_t<hb_pair_t<hb_codepoint_t, const IndexSubtableRecord*>> lookup;
580     build_lookup (c, bitmap_size_context, &lookup);
581     if (unlikely (!c->serializer->propagate_error (lookup)))
582       return false;
583
584     bitmap_size_context->size = 0;
585     bitmap_size_context->num_tables = 0;
586     hb_vector_t<IndexSubtableRecord> records;
587     for (unsigned int start = 0; start < lookup.length;)
588     {
589       if (unlikely (!lookup[start].second->add_new_record (c, bitmap_size_context, &lookup, this, &start, &records)))
590       {
591         // Discard any leftover pushes to the serializer from successful records.
592         for (unsigned int i = 0; i < records.length; i++)
593           c->serializer->pop_discard ();
594         return_trace (false);
595       }
596     }
597
598     /* Workaround to ensure offset ordering is from least to greatest when
599      * resolving links. */
600     hb_vector_t<hb_serialize_context_t::objidx_t> objidxs;
601     for (unsigned int i = 0; i < records.length; i++)
602       objidxs.push (c->serializer->pop_pack ());
603     for (unsigned int i = 0; i < records.length; i++)
604     {
605       IndexSubtableRecord* record = c->serializer->embed (records[i]);
606       if (unlikely (!record)) return_trace (false);
607       c->serializer->add_link (record->offsetToSubtable, objidxs[records.length - 1 - i]);
608     }
609     return_trace (true);
610   }
611
612   public:
613   const IndexSubtableRecord* find_table (hb_codepoint_t glyph, unsigned int numTables) const
614   {
615     for (unsigned int i = 0; i < numTables; ++i)
616     {
617       unsigned int firstGlyphIndex = indexSubtablesZ[i].firstGlyphIndex;
618       unsigned int lastGlyphIndex = indexSubtablesZ[i].lastGlyphIndex;
619       if (firstGlyphIndex <= glyph && glyph <= lastGlyphIndex)
620         return &indexSubtablesZ[i];
621     }
622     return nullptr;
623   }
624
625   protected:
626   UnsizedArrayOf<IndexSubtableRecord>   indexSubtablesZ;
627 };
628
629 struct BitmapSizeTable
630 {
631   friend struct CBLC;
632   friend struct CBDT;
633
634   bool sanitize (hb_sanitize_context_t *c, const void *base) const
635   {
636     TRACE_SANITIZE (this);
637     return_trace (c->check_struct (this) &&
638                   indexSubtableArrayOffset.sanitize (c, base, numberOfIndexSubtables) &&
639                   horizontal.sanitize (c) &&
640                   vertical.sanitize (c));
641   }
642
643   const IndexSubtableRecord *
644   find_table (hb_codepoint_t glyph, const void *base, const void **out_base) const
645   {
646     *out_base = &(base+indexSubtableArrayOffset);
647     return (base+indexSubtableArrayOffset).find_table (glyph, numberOfIndexSubtables);
648   }
649
650   bool
651   subset (hb_subset_context_t *c, const void *base,
652           const char *cbdt, unsigned int cbdt_length,
653           hb_vector_t<char> *cbdt_prime /* INOUT */) const
654   {
655     TRACE_SUBSET (this);
656     auto *out_table = c->serializer->embed (this);
657     if (unlikely (!out_table)) return_trace (false);
658
659     cblc_bitmap_size_subset_context_t bitmap_size_context;
660     bitmap_size_context.cbdt = cbdt;
661     bitmap_size_context.cbdt_length = cbdt_length;
662     bitmap_size_context.cbdt_prime = cbdt_prime;
663     bitmap_size_context.size = indexTablesSize;
664     bitmap_size_context.num_tables = numberOfIndexSubtables;
665     bitmap_size_context.start_glyph = 1;
666     bitmap_size_context.end_glyph = 0;
667
668     if (!out_table->indexSubtableArrayOffset.serialize_subset (c,
669                                                                indexSubtableArrayOffset,
670                                                                base,
671                                                                &bitmap_size_context))
672       return_trace (false);
673     if (!bitmap_size_context.size ||
674         !bitmap_size_context.num_tables ||
675         bitmap_size_context.start_glyph > bitmap_size_context.end_glyph)
676       return_trace (false);
677
678     out_table->indexTablesSize = bitmap_size_context.size;
679     out_table->numberOfIndexSubtables = bitmap_size_context.num_tables;
680     out_table->startGlyphIndex = bitmap_size_context.start_glyph;
681     out_table->endGlyphIndex = bitmap_size_context.end_glyph;
682     return_trace (true);
683   }
684
685   protected:
686   NNOffset32To<IndexSubtableArray>
687                         indexSubtableArrayOffset;
688   HBUINT32              indexTablesSize;
689   HBUINT32              numberOfIndexSubtables;
690   HBUINT32              colorRef;
691   SBitLineMetrics       horizontal;
692   SBitLineMetrics       vertical;
693   HBGlyphID16           startGlyphIndex;
694   HBGlyphID16           endGlyphIndex;
695   HBUINT8               ppemX;
696   HBUINT8               ppemY;
697   HBUINT8               bitDepth;
698   HBINT8                flags;
699   public:
700   DEFINE_SIZE_STATIC (48);
701 };
702
703
704 /*
705  * Glyph Bitmap Data Formats.
706  */
707
708 struct GlyphBitmapDataFormat17
709 {
710   SmallGlyphMetrics     glyphMetrics;
711   Array32Of<HBUINT8>    data;
712   public:
713   DEFINE_SIZE_ARRAY (9, data);
714 };
715
716 struct GlyphBitmapDataFormat18
717 {
718   BigGlyphMetrics       glyphMetrics;
719   Array32Of<HBUINT8>    data;
720   public:
721   DEFINE_SIZE_ARRAY (12, data);
722 };
723
724 struct GlyphBitmapDataFormat19
725 {
726   Array32Of<HBUINT8>    data;
727   public:
728   DEFINE_SIZE_ARRAY (4, data);
729 };
730
731 struct CBLC
732 {
733   friend struct CBDT;
734
735   static constexpr hb_tag_t tableTag = HB_OT_TAG_CBLC;
736
737   bool sanitize (hb_sanitize_context_t *c) const
738   {
739     TRACE_SANITIZE (this);
740     return_trace (c->check_struct (this) &&
741                   likely (version.major == 2 || version.major == 3) &&
742                   sizeTables.sanitize (c, this));
743   }
744
745   static bool
746   sink_cbdt (hb_subset_context_t *c, hb_vector_t<char>* cbdt_prime)
747   {
748     hb_blob_t *cbdt_prime_blob = hb_blob_create (cbdt_prime->arrayZ,
749                                                  cbdt_prime->length,
750                                                  HB_MEMORY_MODE_WRITABLE,
751                                                  cbdt_prime->arrayZ,
752                                                  hb_free);
753     cbdt_prime->init ();  // Leak arrayZ to the blob.
754     bool ret = c->plan->add_table (HB_OT_TAG_CBDT, cbdt_prime_blob);
755     hb_blob_destroy (cbdt_prime_blob);
756     return ret;
757   }
758
759   bool
760   subset_size_table (hb_subset_context_t *c, const BitmapSizeTable& table,
761                      const char *cbdt /* IN */, unsigned int cbdt_length,
762                      CBLC *cblc_prime /* INOUT */, hb_vector_t<char> *cbdt_prime /* INOUT */) const
763   {
764     TRACE_SUBSET (this);
765     cblc_prime->sizeTables.len++;
766
767     auto snap = c->serializer->snapshot ();
768     auto cbdt_prime_len = cbdt_prime->length;
769
770     if (!table.subset (c, this, cbdt, cbdt_length, cbdt_prime))
771     {
772       cblc_prime->sizeTables.len--;
773       c->serializer->revert (snap);
774       cbdt_prime->shrink (cbdt_prime_len);
775       return_trace (false);
776     }
777     return_trace (true);
778   }
779
780   // Implemented in cc file as it depends on definition of CBDT.
781   HB_INTERNAL bool subset (hb_subset_context_t *c) const;
782
783   protected:
784   const BitmapSizeTable &choose_strike (hb_font_t *font) const
785   {
786     unsigned count = sizeTables.len;
787     if (unlikely (!count))
788       return Null (BitmapSizeTable);
789
790     unsigned int requested_ppem = hb_max (font->x_ppem, font->y_ppem);
791     if (!requested_ppem)
792       requested_ppem = 1<<30; /* Choose largest strike. */
793     unsigned int best_i = 0;
794     unsigned int best_ppem = hb_max (sizeTables[0].ppemX, sizeTables[0].ppemY);
795
796     for (unsigned int i = 1; i < count; i++)
797     {
798       unsigned int ppem = hb_max (sizeTables[i].ppemX, sizeTables[i].ppemY);
799       if ((requested_ppem <= ppem && ppem < best_ppem) ||
800           (requested_ppem > best_ppem && ppem > best_ppem))
801       {
802         best_i = i;
803         best_ppem = ppem;
804       }
805     }
806
807     return sizeTables[best_i];
808   }
809
810   protected:
811   FixedVersion<>                version;
812   Array32Of<BitmapSizeTable>    sizeTables;
813   public:
814   DEFINE_SIZE_ARRAY (8, sizeTables);
815 };
816
817 struct CBDT
818 {
819   static constexpr hb_tag_t tableTag = HB_OT_TAG_CBDT;
820
821   struct accelerator_t
822   {
823     accelerator_t (hb_face_t *face)
824     {
825       this->cblc = hb_sanitize_context_t ().reference_table<CBLC> (face);
826       this->cbdt = hb_sanitize_context_t ().reference_table<CBDT> (face);
827
828       upem = hb_face_get_upem (face);
829     }
830     ~accelerator_t ()
831     {
832       this->cblc.destroy ();
833       this->cbdt.destroy ();
834     }
835
836     bool
837     get_extents (hb_font_t *font, hb_codepoint_t glyph, hb_glyph_extents_t *extents, bool scale = true) const
838     {
839       const void *base;
840       const BitmapSizeTable &strike = this->cblc->choose_strike (font);
841       const IndexSubtableRecord *subtable_record = strike.find_table (glyph, cblc, &base);
842       if (!subtable_record || !strike.ppemX || !strike.ppemY)
843         return false;
844
845       if (subtable_record->get_extents (extents, base, scale))
846         return true;
847
848       unsigned int image_offset = 0, image_length = 0, image_format = 0;
849       if (!subtable_record->get_image_data (glyph, base, &image_offset, &image_length, &image_format))
850         return false;
851
852       unsigned int cbdt_len = cbdt.get_length ();
853       if (unlikely (image_offset > cbdt_len || cbdt_len - image_offset < image_length))
854         return false;
855
856       switch (image_format)
857       {
858       case 17: {
859         if (unlikely (image_length < GlyphBitmapDataFormat17::min_size))
860           return false;
861         auto &glyphFormat17 = StructAtOffset<GlyphBitmapDataFormat17> (this->cbdt, image_offset);
862         glyphFormat17.glyphMetrics.get_extents (font, extents, scale);
863         break;
864       }
865       case 18: {
866         if (unlikely (image_length < GlyphBitmapDataFormat18::min_size))
867           return false;
868         auto &glyphFormat18 = StructAtOffset<GlyphBitmapDataFormat18> (this->cbdt, image_offset);
869         glyphFormat18.glyphMetrics.get_extents (font, extents, scale);
870         break;
871       }
872       default: return false; /* TODO: Support other image formats. */
873       }
874
875       /* Convert to font units. */
876       if (scale)
877       {
878         float x_scale = upem / (float) strike.ppemX;
879         float y_scale = upem / (float) strike.ppemY;
880         extents->x_bearing = roundf (extents->x_bearing * x_scale);
881         extents->y_bearing = roundf (extents->y_bearing * y_scale);
882         extents->width = roundf (extents->width * x_scale);
883         extents->height = roundf (extents->height * y_scale);
884       }
885
886       return true;
887     }
888
889     hb_blob_t*
890     reference_png (hb_font_t *font, hb_codepoint_t glyph) const
891     {
892       const void *base;
893       const BitmapSizeTable &strike = this->cblc->choose_strike (font);
894       const IndexSubtableRecord *subtable_record = strike.find_table (glyph, cblc, &base);
895       if (!subtable_record || !strike.ppemX || !strike.ppemY)
896         return hb_blob_get_empty ();
897
898       unsigned int image_offset = 0, image_length = 0, image_format = 0;
899       if (!subtable_record->get_image_data (glyph, base, &image_offset, &image_length, &image_format))
900         return hb_blob_get_empty ();
901
902       unsigned int cbdt_len = cbdt.get_length ();
903       if (unlikely (image_offset > cbdt_len || cbdt_len - image_offset < image_length))
904         return hb_blob_get_empty ();
905
906       switch (image_format)
907       {
908       case 17:
909       {
910         if (unlikely (image_length < GlyphBitmapDataFormat17::min_size))
911           return hb_blob_get_empty ();
912         auto &glyphFormat17 = StructAtOffset<GlyphBitmapDataFormat17> (this->cbdt, image_offset);
913         return hb_blob_create_sub_blob (cbdt.get_blob (),
914                                         image_offset + GlyphBitmapDataFormat17::min_size,
915                                         glyphFormat17.data.len);
916       }
917       case 18:
918       {
919         if (unlikely (image_length < GlyphBitmapDataFormat18::min_size))
920           return hb_blob_get_empty ();
921         auto &glyphFormat18 = StructAtOffset<GlyphBitmapDataFormat18> (this->cbdt, image_offset);
922         return hb_blob_create_sub_blob (cbdt.get_blob (),
923                                         image_offset + GlyphBitmapDataFormat18::min_size,
924                                         glyphFormat18.data.len);
925       }
926       case 19:
927       {
928         if (unlikely (image_length < GlyphBitmapDataFormat19::min_size))
929           return hb_blob_get_empty ();
930         auto &glyphFormat19 = StructAtOffset<GlyphBitmapDataFormat19> (this->cbdt, image_offset);
931         return hb_blob_create_sub_blob (cbdt.get_blob (),
932                                         image_offset + GlyphBitmapDataFormat19::min_size,
933                                         glyphFormat19.data.len);
934       }
935       default: return hb_blob_get_empty (); /* TODO: Support other image formats. */
936       }
937     }
938
939     bool has_data () const { return cbdt.get_length (); }
940
941     bool paint_glyph (hb_font_t *font, hb_codepoint_t glyph, hb_paint_funcs_t *funcs, void *data) const
942     {
943       hb_glyph_extents_t extents;
944       hb_glyph_extents_t pixel_extents;
945       hb_blob_t *blob = reference_png (font, glyph);
946
947       if (unlikely (blob == hb_blob_get_empty ()))
948         return false;
949
950       if (unlikely (!hb_font_get_glyph_extents (font, glyph, &extents)))
951         return false;
952
953       if (unlikely (!get_extents (font, glyph, &pixel_extents, false)))
954         return false;
955
956       bool ret = funcs->image (data,
957                                blob,
958                                pixel_extents.width, -pixel_extents.height,
959                                HB_PAINT_IMAGE_FORMAT_PNG,
960                                font->slant_xy,
961                                &extents);
962
963       hb_blob_destroy (blob);
964       return ret;
965     }
966
967     private:
968     hb_blob_ptr_t<CBLC> cblc;
969     hb_blob_ptr_t<CBDT> cbdt;
970
971     unsigned int upem;
972   };
973
974   bool sanitize (hb_sanitize_context_t *c) const
975   {
976     TRACE_SANITIZE (this);
977     return_trace (c->check_struct (this) &&
978                   likely (version.major == 2 || version.major == 3));
979   }
980
981   protected:
982   FixedVersion<>                version;
983   UnsizedArrayOf<HBUINT8>       dataZ;
984   public:
985   DEFINE_SIZE_ARRAY (4, dataZ);
986 };
987
988 inline bool
989 CBLC::subset (hb_subset_context_t *c) const
990 {
991   TRACE_SUBSET (this);
992
993   // Use a vector as a secondary buffer as the tables need to be built in parallel.
994   hb_vector_t<char> cbdt_prime;
995
996   auto *cblc_prime = c->serializer->start_embed<CBLC> ();
997   if (unlikely (!c->serializer->extend_min (cblc_prime))) return_trace (false);
998   cblc_prime->version = version;
999
1000   hb_blob_t* cbdt_blob = hb_sanitize_context_t ().reference_table<CBDT> (c->plan->source);
1001   unsigned int cbdt_length;
1002   CBDT* cbdt = (CBDT *) hb_blob_get_data (cbdt_blob, &cbdt_length);
1003   if (unlikely (cbdt_length < CBDT::min_size))
1004   {
1005     hb_blob_destroy (cbdt_blob);
1006     return_trace (false);
1007   }
1008   _copy_data_to_cbdt (&cbdt_prime, cbdt, CBDT::min_size);
1009
1010   for (const BitmapSizeTable& table : + sizeTables.iter ())
1011     subset_size_table (c, table, (const char *) cbdt, cbdt_length, cblc_prime, &cbdt_prime);
1012
1013   hb_blob_destroy (cbdt_blob);
1014
1015   return_trace (CBLC::sink_cbdt (c, &cbdt_prime));
1016 }
1017
1018 struct CBDT_accelerator_t : CBDT::accelerator_t {
1019   CBDT_accelerator_t (hb_face_t *face) : CBDT::accelerator_t (face) {}
1020 };
1021
1022
1023 } /* namespace OT */
1024
1025 #endif /* OT_COLOR_CBDT_CBDT_HH */