1 /*
2  * Copyright © 2015  Google, Inc.
3  * Copyright © 2019  Adobe Inc.
4  * Copyright © 2019  Ebrahim Byagowi
5  *
6  *  This is part of HarfBuzz, a text shaping library.
7  *
8  * Permission is hereby granted, without written agreement and without
9  * license or royalty fees, to use, copy, modify, and distribute this
10  * software and its documentation for any purpose, provided that the
11  * above copyright notice and the following two paragraphs appear in
12  * all copies of this software.
13  *
14  * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
15  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
16  * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
17  * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
18  * DAMAGE.
19  *
20  * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
21  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
22  * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
23  * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
24  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
25  *
26  * Google Author(s): Behdad Esfahbod, Garret Rieger, Roderick Sheeter
27  * Adobe Author(s): Michiharu Ariza
28  */
29 
30 #ifndef HB_OT_GLYF_TABLE_HH
31 #define HB_OT_GLYF_TABLE_HH
32 
33 #include "hb-open-type.hh"
34 #include "hb-ot-head-table.hh"
35 #include "hb-ot-hmtx-table.hh"
36 #include "hb-ot-var-gvar-table.hh"
37 #include "hb-draw.hh"
38 
39 namespace OT {
40 
41 
42 /*
43  * loca -- Index to Location
44  * https://docs.microsoft.com/en-us/typography/opentype/spec/loca
45  */
46 #define HB_OT_TAG_loca HB_TAG('l','o','c','a')
47 
48 #ifndef HB_MAX_COMPOSITE_OPERATIONS
49 #define HB_MAX_COMPOSITE_OPERATIONS 100000
50 #endif
51 
52 
53 struct loca
54 {
55   friend struct glyf;
56 
57   static constexpr hb_tag_t tableTag = HB_OT_TAG_loca;
58 
sanitizeOT::loca59   bool sanitize (hb_sanitize_context_t *c HB_UNUSED) const
60   {
61     TRACE_SANITIZE (this);
62     return_trace (true);
63   }
64 
65   protected:
66   UnsizedArrayOf<HBUINT8>
67 		dataZ;	/* Location data. */
68   public:
69   DEFINE_SIZE_MIN (0);	/* In reality, this is UNBOUNDED() type; but since we always
70 			 * check the size externally, allow Null() object of it by
71 			 * defining it _MIN instead. */
72 };
73 
74 
75 /*
76  * glyf -- TrueType Glyph Data
77  * https://docs.microsoft.com/en-us/typography/opentype/spec/glyf
78  */
79 #define HB_OT_TAG_glyf HB_TAG('g','l','y','f')
80 
81 
82 struct glyf
83 {
84   static constexpr hb_tag_t tableTag = HB_OT_TAG_glyf;
85 
sanitizeOT::glyf86   bool sanitize (hb_sanitize_context_t *c HB_UNUSED) const
87   {
88     TRACE_SANITIZE (this);
89     /* Runtime checks as eager sanitizing each glyph is costy */
90     return_trace (true);
91   }
92 
93   template<typename Iterator,
94 	   hb_requires (hb_is_source_of (Iterator, unsigned int))>
95   static bool
_add_loca_and_headOT::glyf96   _add_loca_and_head (hb_subset_plan_t * plan, Iterator padded_offsets, bool use_short_loca)
97   {
98     unsigned num_offsets = padded_offsets.len () + 1;
99     unsigned entry_size = use_short_loca ? 2 : 4;
100     char *loca_prime_data = (char *) hb_calloc (entry_size, num_offsets);
101 
102     if (unlikely (!loca_prime_data)) return false;
103 
104     DEBUG_MSG (SUBSET, nullptr, "loca entry_size %d num_offsets %d size %d",
105 	       entry_size, num_offsets, entry_size * num_offsets);
106 
107     if (use_short_loca)
108       _write_loca (padded_offsets, 1, hb_array ((HBUINT16 *) loca_prime_data, num_offsets));
109     else
110       _write_loca (padded_offsets, 0, hb_array ((HBUINT32 *) loca_prime_data, num_offsets));
111 
112     hb_blob_t *loca_blob = hb_blob_create (loca_prime_data,
113 					   entry_size * num_offsets,
114 					   HB_MEMORY_MODE_WRITABLE,
115 					   loca_prime_data,
116 					   hb_free);
117 
118     bool result = plan->add_table (HB_OT_TAG_loca, loca_blob)
119 	       && _add_head_and_set_loca_version (plan, use_short_loca);
120 
121     hb_blob_destroy (loca_blob);
122     return result;
123   }
124 
125   template<typename IteratorIn, typename IteratorOut,
126 	   hb_requires (hb_is_source_of (IteratorIn, unsigned int)),
127 	   hb_requires (hb_is_sink_of (IteratorOut, unsigned))>
128   static void
_write_locaOT::glyf129   _write_loca (IteratorIn it, unsigned right_shift, IteratorOut dest)
130   {
131     unsigned int offset = 0;
132     dest << 0;
133     + it
134     | hb_map ([=, &offset] (unsigned int padded_size)
135 	      {
136 		offset += padded_size;
137 		DEBUG_MSG (SUBSET, nullptr, "loca entry offset %d", offset);
138 		return offset >> right_shift;
139 	      })
140     | hb_sink (dest)
141     ;
142   }
143 
144   /* requires source of SubsetGlyph complains the identifier isn't declared */
145   template <typename Iterator>
serializeOT::glyf146   bool serialize (hb_serialize_context_t *c,
147 		  Iterator it,
148                   bool use_short_loca,
149 		  const hb_subset_plan_t *plan)
150   {
151     TRACE_SERIALIZE (this);
152     unsigned init_len = c->length ();
153     for (const auto &_ : it) _.serialize (c, use_short_loca, plan);
154 
155     /* As a special case when all glyph in the font are empty, add a zero byte
156      * to the table, so that OTS doesn’t reject it, and to make the table work
157      * on Windows as well.
158      * See https://github.com/khaledhosny/ots/issues/52 */
159     if (init_len == c->length ())
160     {
161       HBUINT8 empty_byte;
162       empty_byte = 0;
163       c->copy (empty_byte);
164     }
165     return_trace (true);
166   }
167 
168   /* Byte region(s) per glyph to output
169      unpadded, hints removed if so requested
170      If we fail to process a glyph we produce an empty (0-length) glyph */
subsetOT::glyf171   bool subset (hb_subset_context_t *c) const
172   {
173     TRACE_SUBSET (this);
174 
175     glyf *glyf_prime = c->serializer->start_embed <glyf> ();
176     if (unlikely (!c->serializer->check_success (glyf_prime))) return_trace (false);
177 
178     hb_vector_t<SubsetGlyph> glyphs;
179     _populate_subset_glyphs (c->plan, &glyphs);
180 
181     auto padded_offsets =
182     + hb_iter (glyphs)
183     | hb_map (&SubsetGlyph::padded_size)
184     ;
185 
186     unsigned max_offset = + padded_offsets | hb_reduce (hb_add, 0);
187     bool use_short_loca = max_offset < 0x1FFFF;
188 
189 
190     glyf_prime->serialize (c->serializer, hb_iter (glyphs), use_short_loca, c->plan);
191     if (!use_short_loca) {
192       padded_offsets =
193           + hb_iter (glyphs)
194           | hb_map (&SubsetGlyph::length)
195           ;
196     }
197 
198 
199     if (unlikely (c->serializer->in_error ())) return_trace (false);
200     return_trace (c->serializer->check_success (_add_loca_and_head (c->plan,
201 								    padded_offsets,
202                                                                     use_short_loca)));
203   }
204 
205   template <typename SubsetGlyph>
206   void
_populate_subset_glyphsOT::glyf207   _populate_subset_glyphs (const hb_subset_plan_t   *plan,
208 			   hb_vector_t<SubsetGlyph> *glyphs /* OUT */) const
209   {
210     OT::glyf::accelerator_t glyf (plan->source);
211 
212     + hb_range (plan->num_output_glyphs ())
213     | hb_map ([&] (hb_codepoint_t new_gid)
214 	      {
215 		SubsetGlyph subset_glyph = {0};
216 		subset_glyph.new_gid = new_gid;
217 
218 		/* should never fail: all old gids should be mapped */
219 		if (!plan->old_gid_for_new_gid (new_gid, &subset_glyph.old_gid))
220 		  return subset_glyph;
221 
222 		if (new_gid == 0 &&
223                     !(plan->flags & HB_SUBSET_FLAGS_NOTDEF_OUTLINE))
224 		  subset_glyph.source_glyph = Glyph ();
225 		else
226 		  subset_glyph.source_glyph = glyf.glyph_for_gid (subset_glyph.old_gid, true);
227 		if (plan->flags & HB_SUBSET_FLAGS_NO_HINTING)
228                   subset_glyph.drop_hints_bytes ();
229 		else
230                   subset_glyph.dest_start = subset_glyph.source_glyph.get_bytes ();
231 		return subset_glyph;
232 	      })
233     | hb_sink (glyphs)
234     ;
235   }
236 
237   static bool
_add_head_and_set_loca_versionOT::glyf238   _add_head_and_set_loca_version (hb_subset_plan_t *plan, bool use_short_loca)
239   {
240     hb_blob_t *head_blob = hb_sanitize_context_t ().reference_table<head> (plan->source);
241     hb_blob_t *head_prime_blob = hb_blob_copy_writable_or_fail (head_blob);
242     hb_blob_destroy (head_blob);
243 
244     if (unlikely (!head_prime_blob))
245       return false;
246 
247     head *head_prime = (head *) hb_blob_get_data_writable (head_prime_blob, nullptr);
248     head_prime->indexToLocFormat = use_short_loca ? 0 : 1;
249     bool success = plan->add_table (HB_OT_TAG_head, head_prime_blob);
250 
251     hb_blob_destroy (head_prime_blob);
252     return success;
253   }
254 
255   struct CompositeGlyphChain
256   {
257     protected:
258     enum composite_glyph_flag_t
259     {
260       ARG_1_AND_2_ARE_WORDS	= 0x0001,
261       ARGS_ARE_XY_VALUES	= 0x0002,
262       ROUND_XY_TO_GRID		= 0x0004,
263       WE_HAVE_A_SCALE		= 0x0008,
264       MORE_COMPONENTS		= 0x0020,
265       WE_HAVE_AN_X_AND_Y_SCALE	= 0x0040,
266       WE_HAVE_A_TWO_BY_TWO	= 0x0080,
267       WE_HAVE_INSTRUCTIONS	= 0x0100,
268       USE_MY_METRICS		= 0x0200,
269       OVERLAP_COMPOUND		= 0x0400,
270       SCALED_COMPONENT_OFFSET	= 0x0800,
271       UNSCALED_COMPONENT_OFFSET = 0x1000
272     };
273 
274     public:
get_sizeOT::glyf::CompositeGlyphChain275     unsigned int get_size () const
276     {
277       unsigned int size = min_size;
278       /* arg1 and 2 are int16 */
279       if (flags & ARG_1_AND_2_ARE_WORDS) size += 4;
280       /* arg1 and 2 are int8 */
281       else size += 2;
282 
283       /* One x 16 bit (scale) */
284       if (flags & WE_HAVE_A_SCALE) size += 2;
285       /* Two x 16 bit (xscale, yscale) */
286       else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) size += 4;
287       /* Four x 16 bit (xscale, scale01, scale10, yscale) */
288       else if (flags & WE_HAVE_A_TWO_BY_TWO) size += 8;
289 
290       return size;
291     }
292 
set_glyph_indexOT::glyf::CompositeGlyphChain293     void set_glyph_index (hb_codepoint_t new_gid) { glyphIndex = new_gid; }
get_glyph_indexOT::glyf::CompositeGlyphChain294     hb_codepoint_t get_glyph_index ()       const { return glyphIndex; }
295 
drop_instructions_flagOT::glyf::CompositeGlyphChain296     void drop_instructions_flag ()  { flags = (uint16_t) flags & ~WE_HAVE_INSTRUCTIONS; }
set_overlaps_flagOT::glyf::CompositeGlyphChain297     void set_overlaps_flag ()
298     {
299       flags = (uint16_t) flags | OVERLAP_COMPOUND;
300     }
301 
has_instructionsOT::glyf::CompositeGlyphChain302     bool has_instructions ()  const { return   flags & WE_HAVE_INSTRUCTIONS; }
303 
has_moreOT::glyf::CompositeGlyphChain304     bool has_more ()          const { return   flags & MORE_COMPONENTS; }
is_use_my_metricsOT::glyf::CompositeGlyphChain305     bool is_use_my_metrics () const { return   flags & USE_MY_METRICS; }
is_anchoredOT::glyf::CompositeGlyphChain306     bool is_anchored ()       const { return !(flags & ARGS_ARE_XY_VALUES); }
get_anchor_pointsOT::glyf::CompositeGlyphChain307     void get_anchor_points (unsigned int &point1, unsigned int &point2) const
308     {
309       const HBUINT8 *p = &StructAfter<const HBUINT8> (glyphIndex);
310       if (flags & ARG_1_AND_2_ARE_WORDS)
311       {
312 	point1 = ((const HBUINT16 *) p)[0];
313 	point2 = ((const HBUINT16 *) p)[1];
314       }
315       else
316       {
317 	point1 = p[0];
318 	point2 = p[1];
319       }
320     }
321 
transform_pointsOT::glyf::CompositeGlyphChain322     void transform_points (contour_point_vector_t &points) const
323     {
324       float matrix[4];
325       contour_point_t trans;
326       if (get_transformation (matrix, trans))
327       {
328 	if (scaled_offsets ())
329 	{
330 	  points.translate (trans);
331 	  points.transform (matrix);
332 	}
333 	else
334 	{
335 	  points.transform (matrix);
336 	  points.translate (trans);
337 	}
338       }
339     }
340 
341     protected:
scaled_offsetsOT::glyf::CompositeGlyphChain342     bool scaled_offsets () const
343     { return (flags & (SCALED_COMPONENT_OFFSET | UNSCALED_COMPONENT_OFFSET)) == SCALED_COMPONENT_OFFSET; }
344 
get_transformationOT::glyf::CompositeGlyphChain345     bool get_transformation (float (&matrix)[4], contour_point_t &trans) const
346     {
347       matrix[0] = matrix[3] = 1.f;
348       matrix[1] = matrix[2] = 0.f;
349 
350       int tx, ty;
351       const HBINT8 *p = &StructAfter<const HBINT8> (glyphIndex);
352       if (flags & ARG_1_AND_2_ARE_WORDS)
353       {
354 	tx = *(const HBINT16 *) p;
355 	p += HBINT16::static_size;
356 	ty = *(const HBINT16 *) p;
357 	p += HBINT16::static_size;
358       }
359       else
360       {
361 	tx = *p++;
362 	ty = *p++;
363       }
364       if (is_anchored ()) tx = ty = 0;
365 
366       trans.init ((float) tx, (float) ty);
367 
368       {
369 	const F2DOT14 *points = (const F2DOT14 *) p;
370 	if (flags & WE_HAVE_A_SCALE)
371 	{
372 	  matrix[0] = matrix[3] = points[0].to_float ();
373 	  return true;
374 	}
375 	else if (flags & WE_HAVE_AN_X_AND_Y_SCALE)
376 	{
377 	  matrix[0] = points[0].to_float ();
378 	  matrix[3] = points[1].to_float ();
379 	  return true;
380 	}
381 	else if (flags & WE_HAVE_A_TWO_BY_TWO)
382 	{
383 	  matrix[0] = points[0].to_float ();
384 	  matrix[1] = points[1].to_float ();
385 	  matrix[2] = points[2].to_float ();
386 	  matrix[3] = points[3].to_float ();
387 	  return true;
388 	}
389       }
390       return tx || ty;
391     }
392 
393     protected:
394     HBUINT16	flags;
395     HBGlyphID16	glyphIndex;
396     public:
397     DEFINE_SIZE_MIN (4);
398   };
399 
400   struct composite_iter_t : hb_iter_with_fallback_t<composite_iter_t, const CompositeGlyphChain &>
401   {
402     typedef const CompositeGlyphChain *__item_t__;
composite_iter_tOT::glyf::composite_iter_t403     composite_iter_t (hb_bytes_t glyph_, __item_t__ current_) :
404         glyph (glyph_), current (nullptr), current_size (0)
405     {
406       set_next (current_);
407     }
408 
composite_iter_tOT::glyf::composite_iter_t409     composite_iter_t () : glyph (hb_bytes_t ()), current (nullptr), current_size (0) {}
410 
__item__OT::glyf::composite_iter_t411     const CompositeGlyphChain &__item__ () const { return *current; }
__more__OT::glyf::composite_iter_t412     bool __more__ () const { return current; }
__next__OT::glyf::composite_iter_t413     void __next__ ()
414     {
415       if (!current->has_more ()) { current = nullptr; return; }
416 
417       set_next (&StructAtOffset<CompositeGlyphChain> (current, current_size));
418     }
operator !=OT::glyf::composite_iter_t419     bool operator != (const composite_iter_t& o) const
420     { return glyph != o.glyph || current != o.current; }
421 
422 
set_nextOT::glyf::composite_iter_t423     void set_next (const CompositeGlyphChain *composite)
424     {
425       if (!glyph.check_range (composite, CompositeGlyphChain::min_size))
426       {
427         current = nullptr;
428         current_size = 0;
429         return;
430       }
431       unsigned size = composite->get_size ();
432       if (!glyph.check_range (composite, size))
433       {
434         current = nullptr;
435         current_size = 0;
436         return;
437       }
438 
439       current = composite;
440       current_size = size;
441     }
442 
443     private:
444     hb_bytes_t glyph;
445     __item_t__ current;
446     unsigned current_size;
447   };
448 
449   enum phantom_point_index_t
450   {
451     PHANTOM_LEFT   = 0,
452     PHANTOM_RIGHT  = 1,
453     PHANTOM_TOP    = 2,
454     PHANTOM_BOTTOM = 3,
455     PHANTOM_COUNT  = 4
456   };
457 
458   struct accelerator_t;
459 
460   struct Glyph
461   {
462     enum simple_glyph_flag_t
463     {
464       FLAG_ON_CURVE       = 0x01,
465       FLAG_X_SHORT        = 0x02,
466       FLAG_Y_SHORT        = 0x04,
467       FLAG_REPEAT         = 0x08,
468       FLAG_X_SAME         = 0x10,
469       FLAG_Y_SAME         = 0x20,
470       FLAG_OVERLAP_SIMPLE = 0x40,
471       FLAG_RESERVED2      = 0x80
472     };
473 
474     private:
475     struct GlyphHeader
476     {
has_dataOT::glyf::Glyph::GlyphHeader477       bool has_data () const { return numberOfContours; }
478 
get_extentsOT::glyf::Glyph::GlyphHeader479       bool get_extents (hb_font_t *font, const accelerator_t &glyf_accelerator,
480 		        hb_codepoint_t gid, hb_glyph_extents_t *extents) const
481       {
482 	/* Undocumented rasterizer behavior: shift glyph to the left by (lsb - xMin), i.e., xMin = lsb */
483 	/* extents->x_bearing = hb_min (glyph_header.xMin, glyph_header.xMax); */
484 	extents->x_bearing = font->em_scale_x (glyf_accelerator.hmtx->get_side_bearing (gid));
485 	extents->y_bearing = font->em_scale_y (hb_max (yMin, yMax));
486 	extents->width     = font->em_scale_x (hb_max (xMin, xMax) - hb_min (xMin, xMax));
487 	extents->height    = font->em_scale_y (hb_min (yMin, yMax) - hb_max (yMin, yMax));
488 
489 	return true;
490       }
491 
492       HBINT16	numberOfContours;
493 			/* If the number of contours is
494 			 * greater than or equal to zero,
495 			 * this is a simple glyph; if negative,
496 			 * this is a composite glyph. */
497       FWORD	xMin;	/* Minimum x for coordinate data. */
498       FWORD	yMin;	/* Minimum y for coordinate data. */
499       FWORD	xMax;	/* Maximum x for coordinate data. */
500       FWORD	yMax;	/* Maximum y for coordinate data. */
501       public:
502       DEFINE_SIZE_STATIC (10);
503     };
504 
505     struct SimpleGlyph
506     {
507       const GlyphHeader &header;
508       hb_bytes_t bytes;
SimpleGlyphOT::glyf::Glyph::SimpleGlyph509       SimpleGlyph (const GlyphHeader &header_, hb_bytes_t bytes_) :
510 	header (header_), bytes (bytes_) {}
511 
instruction_len_offsetOT::glyf::Glyph::SimpleGlyph512       unsigned int instruction_len_offset () const
513       { return GlyphHeader::static_size + 2 * header.numberOfContours; }
514 
lengthOT::glyf::Glyph::SimpleGlyph515       unsigned int length (unsigned int instruction_len) const
516       { return instruction_len_offset () + 2 + instruction_len; }
517 
instructions_lengthOT::glyf::Glyph::SimpleGlyph518       unsigned int instructions_length () const
519       {
520 	unsigned int instruction_length_offset = instruction_len_offset ();
521 	if (unlikely (instruction_length_offset + 2 > bytes.length)) return 0;
522 
523 	const HBUINT16 &instructionLength = StructAtOffset<HBUINT16> (&bytes, instruction_length_offset);
524 	/* Out of bounds of the current glyph */
525 	if (unlikely (length (instructionLength) > bytes.length)) return 0;
526 	return instructionLength;
527       }
528 
trim_paddingOT::glyf::Glyph::SimpleGlyph529       const Glyph trim_padding () const
530       {
531 	/* based on FontTools _g_l_y_f.py::trim */
532 	const uint8_t *glyph = (uint8_t*) bytes.arrayZ;
533 	const uint8_t *glyph_end = glyph + bytes.length;
534 	/* simple glyph w/contours, possibly trimmable */
535 	glyph += instruction_len_offset ();
536 
537 	if (unlikely (glyph + 2 >= glyph_end)) return Glyph ();
538 	unsigned int num_coordinates = StructAtOffset<HBUINT16> (glyph - 2, 0) + 1;
539 	unsigned int num_instructions = StructAtOffset<HBUINT16> (glyph, 0);
540 
541 	glyph += 2 + num_instructions;
542 
543 	unsigned int coord_bytes = 0;
544 	unsigned int coords_with_flags = 0;
545 	while (glyph < glyph_end)
546 	{
547 	  uint8_t flag = *glyph;
548 	  glyph++;
549 
550 	  unsigned int repeat = 1;
551 	  if (flag & FLAG_REPEAT)
552 	  {
553 	    if (unlikely (glyph >= glyph_end)) return Glyph ();
554 	    repeat = *glyph + 1;
555 	    glyph++;
556 	  }
557 
558 	  unsigned int xBytes, yBytes;
559 	  xBytes = yBytes = 0;
560 	  if (flag & FLAG_X_SHORT) xBytes = 1;
561 	  else if ((flag & FLAG_X_SAME) == 0) xBytes = 2;
562 
563 	  if (flag & FLAG_Y_SHORT) yBytes = 1;
564 	  else if ((flag & FLAG_Y_SAME) == 0) yBytes = 2;
565 
566 	  coord_bytes += (xBytes + yBytes) * repeat;
567 	  coords_with_flags += repeat;
568 	  if (coords_with_flags >= num_coordinates) break;
569 	}
570 
571 	if (unlikely (coords_with_flags != num_coordinates)) return Glyph ();
572 	return Glyph (bytes.sub_array (0, bytes.length + coord_bytes - (glyph_end - glyph)));
573       }
574 
575       /* zero instruction length */
drop_hintsOT::glyf::Glyph::SimpleGlyph576       void drop_hints ()
577       {
578 	GlyphHeader &glyph_header = const_cast<GlyphHeader &> (header);
579 	(HBUINT16 &) StructAtOffset<HBUINT16> (&glyph_header, instruction_len_offset ()) = 0;
580       }
581 
drop_hints_bytesOT::glyf::Glyph::SimpleGlyph582       void drop_hints_bytes (hb_bytes_t &dest_start, hb_bytes_t &dest_end) const
583       {
584 	unsigned int instructions_len = instructions_length ();
585 	unsigned int glyph_length = length (instructions_len);
586 	dest_start = bytes.sub_array (0, glyph_length - instructions_len);
587 	dest_end = bytes.sub_array (glyph_length, bytes.length - glyph_length);
588       }
589 
set_overlaps_flagOT::glyf::Glyph::SimpleGlyph590       void set_overlaps_flag ()
591       {
592         if (unlikely (!header.numberOfContours)) return;
593 
594         unsigned flags_offset = length (instructions_length ());
595         if (unlikely (flags_offset + 1 > bytes.length)) return;
596 
597 	HBUINT8 &first_flag = (HBUINT8 &) StructAtOffset<HBUINT16> (&bytes, flags_offset);
598         first_flag = (uint8_t) first_flag | FLAG_OVERLAP_SIMPLE;
599       }
600 
read_pointsOT::glyf::Glyph::SimpleGlyph601       static bool read_points (const HBUINT8 *&p /* IN/OUT */,
602 			       contour_point_vector_t &points_ /* IN/OUT */,
603 			       const hb_bytes_t &bytes,
604 			       void (* setter) (contour_point_t &_, float v),
605 			       const simple_glyph_flag_t short_flag,
606 			       const simple_glyph_flag_t same_flag)
607       {
608 	float v = 0;
609 	for (unsigned i = 0; i < points_.length; i++)
610 	{
611 	  uint8_t flag = points_[i].flag;
612 	  if (flag & short_flag)
613 	  {
614 	    if (unlikely (!bytes.check_range (p))) return false;
615 	    if (flag & same_flag)
616 	      v += *p++;
617 	    else
618 	      v -= *p++;
619 	  }
620 	  else
621 	  {
622 	    if (!(flag & same_flag))
623 	    {
624 	      if (unlikely (!bytes.check_range ((const HBUINT16 *) p))) return false;
625 	      v += *(const HBINT16 *) p;
626 	      p += HBINT16::static_size;
627 	    }
628 	  }
629 	  setter (points_[i], v);
630 	}
631 	return true;
632       }
633 
get_contour_pointsOT::glyf::Glyph::SimpleGlyph634       bool get_contour_points (contour_point_vector_t &points_ /* OUT */,
635 			       bool phantom_only = false) const
636       {
637 	const HBUINT16 *endPtsOfContours = &StructAfter<HBUINT16> (header);
638 	int num_contours = header.numberOfContours;
639 	if (unlikely (!bytes.check_range (&endPtsOfContours[num_contours + 1]))) return false;
640 	unsigned int num_points = endPtsOfContours[num_contours - 1] + 1;
641 
642 	points_.resize (num_points);
643 	for (unsigned int i = 0; i < points_.length; i++) points_[i].init ();
644 	if (phantom_only) return true;
645 
646 	for (int i = 0; i < num_contours; i++)
647 	  points_[endPtsOfContours[i]].is_end_point = true;
648 
649 	/* Skip instructions */
650 	const HBUINT8 *p = &StructAtOffset<HBUINT8> (&endPtsOfContours[num_contours + 1],
651 						     endPtsOfContours[num_contours]);
652 
653 	/* Read flags */
654 	for (unsigned int i = 0; i < num_points; i++)
655 	{
656 	  if (unlikely (!bytes.check_range (p))) return false;
657 	  uint8_t flag = *p++;
658 	  points_[i].flag = flag;
659 	  if (flag & FLAG_REPEAT)
660 	  {
661 	    if (unlikely (!bytes.check_range (p))) return false;
662 	    unsigned int repeat_count = *p++;
663 	    while ((repeat_count-- > 0) && (++i < num_points))
664 	      points_[i].flag = flag;
665 	  }
666 	}
667 
668 	/* Read x & y coordinates */
669 	return read_points (p, points_, bytes, [] (contour_point_t &p, float v) { p.x = v; },
670 			    FLAG_X_SHORT, FLAG_X_SAME)
671 	    && read_points (p, points_, bytes, [] (contour_point_t &p, float v) { p.y = v; },
672 			    FLAG_Y_SHORT, FLAG_Y_SAME);
673       }
674     };
675 
676     struct CompositeGlyph
677     {
678       const GlyphHeader &header;
679       hb_bytes_t bytes;
CompositeGlyphOT::glyf::Glyph::CompositeGlyph680       CompositeGlyph (const GlyphHeader &header_, hb_bytes_t bytes_) :
681 	header (header_), bytes (bytes_) {}
682 
get_iteratorOT::glyf::Glyph::CompositeGlyph683       composite_iter_t get_iterator () const
684       { return composite_iter_t (bytes, &StructAfter<CompositeGlyphChain, GlyphHeader> (header)); }
685 
instructions_lengthOT::glyf::Glyph::CompositeGlyph686       unsigned int instructions_length (hb_bytes_t bytes) const
687       {
688 	unsigned int start = bytes.length;
689 	unsigned int end = bytes.length;
690 	const CompositeGlyphChain *last = nullptr;
691 	for (auto &item : get_iterator ())
692 	  last = &item;
693 	if (unlikely (!last)) return 0;
694 
695 	if (last->has_instructions ())
696 	  start = (char *) last - &bytes + last->get_size ();
697 	if (unlikely (start > end)) return 0;
698 	return end - start;
699       }
700 
701       /* Trimming for composites not implemented.
702        * If removing hints it falls out of that. */
trim_paddingOT::glyf::Glyph::CompositeGlyph703       const Glyph trim_padding () const { return Glyph (bytes); }
704 
drop_hintsOT::glyf::Glyph::CompositeGlyph705       void drop_hints ()
706       {
707 	for (const auto &_ : get_iterator ())
708 	  const_cast<CompositeGlyphChain &> (_).drop_instructions_flag ();
709       }
710 
711       /* Chop instructions off the end */
drop_hints_bytesOT::glyf::Glyph::CompositeGlyph712       void drop_hints_bytes (hb_bytes_t &dest_start) const
713       { dest_start = bytes.sub_array (0, bytes.length - instructions_length (bytes)); }
714 
set_overlaps_flagOT::glyf::Glyph::CompositeGlyph715       void set_overlaps_flag ()
716       {
717         const_cast<CompositeGlyphChain &> (StructAfter<CompositeGlyphChain, GlyphHeader> (header))
718                 .set_overlaps_flag ();
719       }
720     };
721 
722     enum glyph_type_t { EMPTY, SIMPLE, COMPOSITE };
723 
724     public:
get_composite_iteratorOT::glyf::Glyph725     composite_iter_t get_composite_iterator () const
726     {
727       if (type != COMPOSITE) return composite_iter_t ();
728       return CompositeGlyph (*header, bytes).get_iterator ();
729     }
730 
trim_paddingOT::glyf::Glyph731     const Glyph trim_padding () const
732     {
733       switch (type) {
734       case COMPOSITE: return CompositeGlyph (*header, bytes).trim_padding ();
735       case SIMPLE:    return SimpleGlyph (*header, bytes).trim_padding ();
736       default:        return bytes;
737       }
738     }
739 
drop_hintsOT::glyf::Glyph740     void drop_hints ()
741     {
742       switch (type) {
743       case COMPOSITE: CompositeGlyph (*header, bytes).drop_hints (); return;
744       case SIMPLE:    SimpleGlyph (*header, bytes).drop_hints (); return;
745       default:        return;
746       }
747     }
748 
set_overlaps_flagOT::glyf::Glyph749     void set_overlaps_flag ()
750     {
751       switch (type) {
752       case COMPOSITE: CompositeGlyph (*header, bytes).set_overlaps_flag (); return;
753       case SIMPLE:    SimpleGlyph (*header, bytes).set_overlaps_flag (); return;
754       default:        return;
755       }
756     }
757 
drop_hints_bytesOT::glyf::Glyph758     void drop_hints_bytes (hb_bytes_t &dest_start, hb_bytes_t &dest_end) const
759     {
760       switch (type) {
761       case COMPOSITE: CompositeGlyph (*header, bytes).drop_hints_bytes (dest_start); return;
762       case SIMPLE:    SimpleGlyph (*header, bytes).drop_hints_bytes (dest_start, dest_end); return;
763       default:        return;
764       }
765     }
766 
767     /* Note: Recursively calls itself.
768      * all_points includes phantom points
769      */
get_pointsOT::glyf::Glyph770     bool get_points (hb_font_t *font, const accelerator_t &glyf_accelerator,
771 		     contour_point_vector_t &all_points /* OUT */,
772 		     bool phantom_only = false,
773 		     unsigned int depth = 0) const
774     {
775       if (unlikely (depth > HB_MAX_NESTING_LEVEL)) return false;
776       contour_point_vector_t points;
777 
778       switch (type) {
779       case COMPOSITE:
780       {
781 	/* pseudo component points for each component in composite glyph */
782 	unsigned num_points = hb_len (CompositeGlyph (*header, bytes).get_iterator ());
783 	if (unlikely (!points.resize (num_points))) return false;
784 	for (unsigned i = 0; i < points.length; i++)
785 	  points[i].init ();
786 	break;
787       }
788       case SIMPLE:
789 	if (unlikely (!SimpleGlyph (*header, bytes).get_contour_points (points, phantom_only)))
790 	  return false;
791 	break;
792       }
793 
794       /* Init phantom points */
795       if (unlikely (!points.resize (points.length + PHANTOM_COUNT))) return false;
796       hb_array_t<contour_point_t> phantoms = points.sub_array (points.length - PHANTOM_COUNT, PHANTOM_COUNT);
797       {
798 	for (unsigned i = 0; i < PHANTOM_COUNT; ++i) phantoms[i].init ();
799 	int h_delta = (int) header->xMin -
800 		      glyf_accelerator.hmtx->get_side_bearing (gid);
801 	int v_orig  = (int) header->yMax +
802 #ifndef HB_NO_VERTICAL
803 		      glyf_accelerator.vmtx->get_side_bearing (gid)
804 #else
805 		      0
806 #endif
807 		      ;
808 	unsigned h_adv = glyf_accelerator.hmtx->get_advance (gid);
809 	unsigned v_adv =
810 #ifndef HB_NO_VERTICAL
811 			 glyf_accelerator.vmtx->get_advance (gid)
812 #else
813 			 - font->face->get_upem ()
814 #endif
815 			 ;
816 	phantoms[PHANTOM_LEFT].x = h_delta;
817 	phantoms[PHANTOM_RIGHT].x = h_adv + h_delta;
818 	phantoms[PHANTOM_TOP].y = v_orig;
819 	phantoms[PHANTOM_BOTTOM].y = v_orig - (int) v_adv;
820       }
821 
822 #ifndef HB_NO_VAR
823       if (unlikely (!glyf_accelerator.gvar->apply_deltas_to_points (gid, font, points.as_array ())))
824 	return false;
825 #endif
826 
827       switch (type) {
828       case SIMPLE:
829 	all_points.extend (points.as_array ());
830 	break;
831       case COMPOSITE:
832       {
833 	unsigned int comp_index = 0;
834 	for (auto &item : get_composite_iterator ())
835 	{
836 	  contour_point_vector_t comp_points;
837 	  if (unlikely (!glyf_accelerator.glyph_for_gid (item.get_glyph_index ())
838 					 .get_points (font, glyf_accelerator, comp_points,
839 			 			      phantom_only, depth + 1)
840 			|| comp_points.length < PHANTOM_COUNT))
841 	    return false;
842 
843 	  /* Copy phantom points from component if USE_MY_METRICS flag set */
844 	  if (item.is_use_my_metrics ())
845 	    for (unsigned int i = 0; i < PHANTOM_COUNT; i++)
846 	      phantoms[i] = comp_points[comp_points.length - PHANTOM_COUNT + i];
847 
848 	  /* Apply component transformation & translation */
849 	  item.transform_points (comp_points);
850 
851 	  /* Apply translation from gvar */
852 	  comp_points.translate (points[comp_index]);
853 
854 	  if (item.is_anchored ())
855 	  {
856 	    unsigned int p1, p2;
857 	    item.get_anchor_points (p1, p2);
858 	    if (likely (p1 < all_points.length && p2 < comp_points.length))
859 	    {
860 	      contour_point_t delta;
861 	      delta.init (all_points[p1].x - comp_points[p2].x,
862 			  all_points[p1].y - comp_points[p2].y);
863 
864 	      comp_points.translate (delta);
865 	    }
866 	  }
867 
868 	  all_points.extend (comp_points.sub_array (0, comp_points.length - PHANTOM_COUNT));
869 
870 	  comp_index++;
871 	}
872 
873 	all_points.extend (phantoms);
874       } break;
875       default:
876 	all_points.extend (phantoms);
877       }
878 
879       if (depth == 0) /* Apply at top level */
880       {
881 	/* Undocumented rasterizer behavior:
882 	 * Shift points horizontally by the updated left side bearing
883 	 */
884 	contour_point_t delta;
885 	delta.init (-phantoms[PHANTOM_LEFT].x, 0.f);
886 	if (delta.x) all_points.translate (delta);
887       }
888 
889       return true;
890     }
891 
get_extentsOT::glyf::Glyph892     bool get_extents (hb_font_t *font, const accelerator_t &glyf_accelerator,
893 		      hb_glyph_extents_t *extents) const
894     {
895       if (type == EMPTY) return true; /* Empty glyph; zero extents. */
896       return header->get_extents (font, glyf_accelerator, gid, extents);
897     }
898 
get_bytesOT::glyf::Glyph899     hb_bytes_t get_bytes () const { return bytes; }
900 
GlyphOT::glyf::Glyph901     Glyph (hb_bytes_t bytes_ = hb_bytes_t (),
902 	   hb_codepoint_t gid_ = (hb_codepoint_t) -1) : bytes (bytes_), gid (gid_),
903 							header (bytes.as<GlyphHeader> ())
904     {
905       int num_contours = header->numberOfContours;
906       if (unlikely (num_contours == 0)) type = EMPTY;
907       else if (num_contours > 0) type = SIMPLE;
908       else type = COMPOSITE; /* negative numbers */
909     }
910 
911     protected:
912     hb_bytes_t bytes;
913     hb_codepoint_t gid;
914     const GlyphHeader *header;
915     unsigned type;
916   };
917 
918   struct accelerator_t
919   {
accelerator_tOT::glyf::accelerator_t920     accelerator_t (hb_face_t *face)
921     {
922       short_offset = false;
923       num_glyphs = 0;
924       loca_table = nullptr;
925       glyf_table = nullptr;
926 #ifndef HB_NO_VAR
927       gvar = nullptr;
928 #endif
929       hmtx = nullptr;
930 #ifndef HB_NO_VERTICAL
931       vmtx = nullptr;
932 #endif
933       const OT::head &head = *face->table.head;
934       if (head.indexToLocFormat > 1 || head.glyphDataFormat > 0)
935 	/* Unknown format.  Leave num_glyphs=0, that takes care of disabling us. */
936 	return;
937       short_offset = 0 == head.indexToLocFormat;
938 
939       loca_table = hb_sanitize_context_t ().reference_table<loca> (face);
940       glyf_table = hb_sanitize_context_t ().reference_table<glyf> (face);
941 #ifndef HB_NO_VAR
942       gvar = face->table.gvar;
943 #endif
944       hmtx = face->table.hmtx;
945 #ifndef HB_NO_VERTICAL
946       vmtx = face->table.vmtx;
947 #endif
948 
949       num_glyphs = hb_max (1u, loca_table.get_length () / (short_offset ? 2 : 4)) - 1;
950       num_glyphs = hb_min (num_glyphs, face->get_num_glyphs ());
951     }
~accelerator_tOT::glyf::accelerator_t952     ~accelerator_t ()
953     {
954       loca_table.destroy ();
955       glyf_table.destroy ();
956     }
957 
958     protected:
959     template<typename T>
get_pointsOT::glyf::accelerator_t960     bool get_points (hb_font_t *font, hb_codepoint_t gid, T consumer) const
961     {
962       if (gid >= num_glyphs) return false;
963 
964       /* Making this allocfree is not that easy
965 	 https://github.com/harfbuzz/harfbuzz/issues/2095
966 	 mostly because of gvar handling in VF fonts,
967 	 perhaps a separate path for non-VF fonts can be considered */
968       contour_point_vector_t all_points;
969 
970       bool phantom_only = !consumer.is_consuming_contour_points ();
971       if (unlikely (!glyph_for_gid (gid).get_points (font, *this, all_points, phantom_only)))
972 	return false;
973 
974       if (consumer.is_consuming_contour_points ())
975       {
976 	for (unsigned point_index = 0; point_index + 4 < all_points.length; ++point_index)
977 	  consumer.consume_point (all_points[point_index]);
978 	consumer.points_end ();
979       }
980 
981       /* Where to write phantoms, nullptr if not requested */
982       contour_point_t *phantoms = consumer.get_phantoms_sink ();
983       if (phantoms)
984 	for (unsigned i = 0; i < PHANTOM_COUNT; ++i)
985 	  phantoms[i] = all_points[all_points.length - PHANTOM_COUNT + i];
986 
987       return true;
988     }
989 
990 #ifndef HB_NO_VAR
991     struct points_aggregator_t
992     {
993       hb_font_t *font;
994       hb_glyph_extents_t *extents;
995       contour_point_t *phantoms;
996 
997       struct contour_bounds_t
998       {
contour_bounds_tOT::glyf::accelerator_t::points_aggregator_t::contour_bounds_t999 	contour_bounds_t () { min_x = min_y = FLT_MAX; max_x = max_y = -FLT_MAX; }
1000 
addOT::glyf::accelerator_t::points_aggregator_t::contour_bounds_t1001 	void add (const contour_point_t &p)
1002 	{
1003 	  min_x = hb_min (min_x, p.x);
1004 	  min_y = hb_min (min_y, p.y);
1005 	  max_x = hb_max (max_x, p.x);
1006 	  max_y = hb_max (max_y, p.y);
1007 	}
1008 
emptyOT::glyf::accelerator_t::points_aggregator_t::contour_bounds_t1009 	bool empty () const { return (min_x >= max_x) || (min_y >= max_y); }
1010 
get_extentsOT::glyf::accelerator_t::points_aggregator_t::contour_bounds_t1011 	void get_extents (hb_font_t *font, hb_glyph_extents_t *extents)
1012 	{
1013 	  if (unlikely (empty ()))
1014 	  {
1015 	    extents->width = 0;
1016 	    extents->x_bearing = 0;
1017 	    extents->height = 0;
1018 	    extents->y_bearing = 0;
1019 	    return;
1020 	  }
1021 	  extents->x_bearing = font->em_scalef_x (min_x);
1022 	  extents->width = font->em_scalef_x (max_x) - extents->x_bearing;
1023 	  extents->y_bearing = font->em_scalef_y (max_y);
1024 	  extents->height = font->em_scalef_y (min_y) - extents->y_bearing;
1025 	}
1026 
1027 	protected:
1028 	float min_x, min_y, max_x, max_y;
1029       } bounds;
1030 
points_aggregator_tOT::glyf::accelerator_t::points_aggregator_t1031       points_aggregator_t (hb_font_t *font_, hb_glyph_extents_t *extents_, contour_point_t *phantoms_)
1032       {
1033 	font = font_;
1034 	extents = extents_;
1035 	phantoms = phantoms_;
1036 	if (extents) bounds = contour_bounds_t ();
1037       }
1038 
consume_pointOT::glyf::accelerator_t::points_aggregator_t1039       void consume_point (const contour_point_t &point) { bounds.add (point); }
points_endOT::glyf::accelerator_t::points_aggregator_t1040       void points_end () { bounds.get_extents (font, extents); }
1041 
is_consuming_contour_pointsOT::glyf::accelerator_t::points_aggregator_t1042       bool is_consuming_contour_points () { return extents; }
get_phantoms_sinkOT::glyf::accelerator_t::points_aggregator_t1043       contour_point_t *get_phantoms_sink () { return phantoms; }
1044     };
1045 
1046     public:
1047     unsigned
get_advance_varOT::glyf::accelerator_t1048     get_advance_var (hb_font_t *font, hb_codepoint_t gid, bool is_vertical) const
1049     {
1050       if (unlikely (gid >= num_glyphs)) return 0;
1051 
1052       bool success = false;
1053 
1054       contour_point_t phantoms[PHANTOM_COUNT];
1055       if (likely (font->num_coords == gvar->get_axis_count ()))
1056 	success = get_points (font, gid, points_aggregator_t (font, nullptr, phantoms));
1057 
1058       if (unlikely (!success))
1059 	return
1060 #ifndef HB_NO_VERTICAL
1061 	  is_vertical ? vmtx->get_advance (gid) :
1062 #endif
1063 	  hmtx->get_advance (gid);
1064 
1065       float result = is_vertical
1066 		   ? phantoms[PHANTOM_TOP].y - phantoms[PHANTOM_BOTTOM].y
1067 		   : phantoms[PHANTOM_RIGHT].x - phantoms[PHANTOM_LEFT].x;
1068       return hb_clamp (roundf (result), 0.f, (float) UINT_MAX / 2);
1069     }
1070 
get_side_bearing_varOT::glyf::accelerator_t1071     int get_side_bearing_var (hb_font_t *font, hb_codepoint_t gid, bool is_vertical) const
1072     {
1073       if (unlikely (gid >= num_glyphs)) return 0;
1074 
1075       hb_glyph_extents_t extents;
1076 
1077       contour_point_t phantoms[PHANTOM_COUNT];
1078       if (unlikely (!get_points (font, gid, points_aggregator_t (font, &extents, phantoms))))
1079 	return
1080 #ifndef HB_NO_VERTICAL
1081 	  is_vertical ? vmtx->get_side_bearing (gid) :
1082 #endif
1083 	  hmtx->get_side_bearing (gid);
1084 
1085       return is_vertical
1086 	   ? ceilf (phantoms[PHANTOM_TOP].y) - extents.y_bearing
1087 	   : floorf (phantoms[PHANTOM_LEFT].x);
1088     }
1089 #endif
1090 
1091     public:
get_extentsOT::glyf::accelerator_t1092     bool get_extents (hb_font_t *font, hb_codepoint_t gid, hb_glyph_extents_t *extents) const
1093     {
1094       if (unlikely (gid >= num_glyphs)) return false;
1095 
1096 #ifndef HB_NO_VAR
1097       if (font->num_coords && font->num_coords == gvar->get_axis_count ())
1098 	return get_points (font, gid, points_aggregator_t (font, extents, nullptr));
1099 #endif
1100       return glyph_for_gid (gid).get_extents (font, *this, extents);
1101     }
1102 
1103     const Glyph
glyph_for_gidOT::glyf::accelerator_t1104     glyph_for_gid (hb_codepoint_t gid, bool needs_padding_removal = false) const
1105     {
1106       if (unlikely (gid >= num_glyphs)) return Glyph ();
1107 
1108       unsigned int start_offset, end_offset;
1109 
1110       if (short_offset)
1111       {
1112 	const HBUINT16 *offsets = (const HBUINT16 *) loca_table->dataZ.arrayZ;
1113 	start_offset = 2 * offsets[gid];
1114 	end_offset   = 2 * offsets[gid + 1];
1115       }
1116       else
1117       {
1118 	const HBUINT32 *offsets = (const HBUINT32 *) loca_table->dataZ.arrayZ;
1119 	start_offset = offsets[gid];
1120 	end_offset   = offsets[gid + 1];
1121       }
1122 
1123       if (unlikely (start_offset > end_offset || end_offset > glyf_table.get_length ()))
1124 	return Glyph ();
1125 
1126       Glyph glyph (hb_bytes_t ((const char *) this->glyf_table + start_offset,
1127 			       end_offset - start_offset), gid);
1128       return needs_padding_removal ? glyph.trim_padding () : glyph;
1129     }
1130 
1131     unsigned
add_gid_and_childrenOT::glyf::accelerator_t1132     add_gid_and_children (hb_codepoint_t gid,
1133 			  hb_set_t *gids_to_retain,
1134 			  unsigned depth = 0,
1135 			  unsigned operation_count = 0) const
1136     {
1137       if (unlikely (depth++ > HB_MAX_NESTING_LEVEL)) return operation_count;
1138       if (unlikely (operation_count++ > HB_MAX_COMPOSITE_OPERATIONS)) return operation_count;
1139       /* Check if is already visited */
1140       if (gids_to_retain->has (gid)) return operation_count;
1141 
1142       gids_to_retain->add (gid);
1143 
1144       auto it = glyph_for_gid (gid).get_composite_iterator ();
1145       while (it)
1146       {
1147         auto item = *(it++);
1148         operation_count =
1149             add_gid_and_children (item.get_glyph_index (), gids_to_retain, depth, operation_count);
1150       }
1151 
1152       return operation_count;
1153     }
1154 
1155 #ifdef HB_EXPERIMENTAL_API
1156     struct path_builder_t
1157     {
1158       hb_font_t *font;
1159       draw_helper_t *draw_helper;
1160 
1161       struct optional_point_t
1162       {
optional_point_tOT::glyf::accelerator_t::path_builder_t::optional_point_t1163 	optional_point_t () { has_data = false; }
optional_point_tOT::glyf::accelerator_t::path_builder_t::optional_point_t1164 	optional_point_t (float x_, float y_) { x = x_; y = y_; has_data = true; }
1165 
1166 	bool has_data;
1167 	float x;
1168 	float y;
1169 
lerpOT::glyf::accelerator_t::path_builder_t::optional_point_t1170 	optional_point_t lerp (optional_point_t p, float t)
1171 	{ return optional_point_t (x + t * (p.x - x), y + t * (p.y - y)); }
1172       } first_oncurve, first_offcurve, last_offcurve;
1173 
path_builder_tOT::glyf::accelerator_t::path_builder_t1174       path_builder_t (hb_font_t *font_, draw_helper_t &draw_helper_)
1175       {
1176 	font = font_;
1177 	draw_helper = &draw_helper_;
1178 	first_oncurve = first_offcurve = last_offcurve = optional_point_t ();
1179       }
1180 
1181       /* based on https://github.com/RazrFalcon/ttf-parser/blob/4f32821/src/glyf.rs#L287
1182 	 See also:
1183 	 * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM01/Chap1.html
1184 	 * https://stackoverflow.com/a/20772557 */
consume_pointOT::glyf::accelerator_t::path_builder_t1185       void consume_point (const contour_point_t &point)
1186       {
1187 	/* Skip empty contours */
1188 	if (unlikely (point.is_end_point && !first_oncurve.has_data && !first_offcurve.has_data))
1189 	  return;
1190 
1191 	bool is_on_curve = point.flag & Glyph::FLAG_ON_CURVE;
1192 	optional_point_t p (point.x, point.y);
1193 	if (!first_oncurve.has_data)
1194 	{
1195 	  if (is_on_curve)
1196 	  {
1197 	    first_oncurve = p;
1198 	    draw_helper->move_to (font->em_scalef_x (p.x), font->em_scalef_y (p.y));
1199 	  }
1200 	  else
1201 	  {
1202 	    if (first_offcurve.has_data)
1203 	    {
1204 	      optional_point_t mid = first_offcurve.lerp (p, .5f);
1205 	      first_oncurve = mid;
1206 	      last_offcurve = p;
1207 	      draw_helper->move_to (font->em_scalef_x (mid.x), font->em_scalef_y (mid.y));
1208 	    }
1209 	    else
1210 	      first_offcurve = p;
1211 	  }
1212 	}
1213 	else
1214 	{
1215 	  if (last_offcurve.has_data)
1216 	  {
1217 	    if (is_on_curve)
1218 	    {
1219 	      draw_helper->quadratic_to (font->em_scalef_x (last_offcurve.x), font->em_scalef_y (last_offcurve.y),
1220 					 font->em_scalef_x (p.x), font->em_scalef_y (p.y));
1221 	      last_offcurve = optional_point_t ();
1222 	    }
1223 	    else
1224 	    {
1225 	      optional_point_t mid = last_offcurve.lerp (p, .5f);
1226 	      draw_helper->quadratic_to (font->em_scalef_x (last_offcurve.x), font->em_scalef_y (last_offcurve.y),
1227 					 font->em_scalef_x (mid.x), font->em_scalef_y (mid.y));
1228 	      last_offcurve = p;
1229 	    }
1230 	  }
1231 	  else
1232 	  {
1233 	    if (is_on_curve)
1234 	      draw_helper->line_to (font->em_scalef_x (p.x), font->em_scalef_y (p.y));
1235 	    else
1236 	      last_offcurve = p;
1237 	  }
1238 	}
1239 
1240 	if (point.is_end_point)
1241 	{
1242 	  if (first_offcurve.has_data && last_offcurve.has_data)
1243 	  {
1244 	    optional_point_t mid = last_offcurve.lerp (first_offcurve, .5f);
1245 	    draw_helper->quadratic_to (font->em_scalef_x (last_offcurve.x), font->em_scalef_y (last_offcurve.y),
1246 				       font->em_scalef_x (mid.x), font->em_scalef_y (mid.y));
1247 	    last_offcurve = optional_point_t ();
1248 	    /* now check the rest */
1249 	  }
1250 
1251 	  if (first_offcurve.has_data && first_oncurve.has_data)
1252 	    draw_helper->quadratic_to (font->em_scalef_x (first_offcurve.x), font->em_scalef_y (first_offcurve.y),
1253 				       font->em_scalef_x (first_oncurve.x), font->em_scalef_y (first_oncurve.y));
1254 	  else if (last_offcurve.has_data && first_oncurve.has_data)
1255 	    draw_helper->quadratic_to (font->em_scalef_x (last_offcurve.x), font->em_scalef_y (last_offcurve.y),
1256 				       font->em_scalef_x (first_oncurve.x), font->em_scalef_y (first_oncurve.y));
1257 	  else if (first_oncurve.has_data)
1258 	    draw_helper->line_to (font->em_scalef_x (first_oncurve.x), font->em_scalef_y (first_oncurve.y));
1259 
1260 	  /* Getting ready for the next contour */
1261 	  first_oncurve = first_offcurve = last_offcurve = optional_point_t ();
1262 	  draw_helper->end_path ();
1263 	}
1264       }
points_endOT::glyf::accelerator_t::path_builder_t1265       void points_end () {}
1266 
is_consuming_contour_pointsOT::glyf::accelerator_t::path_builder_t1267       bool is_consuming_contour_points () { return true; }
get_phantoms_sinkOT::glyf::accelerator_t::path_builder_t1268       contour_point_t *get_phantoms_sink () { return nullptr; }
1269     };
1270 
1271     bool
get_pathOT::glyf::accelerator_t1272     get_path (hb_font_t *font, hb_codepoint_t gid, draw_helper_t &draw_helper) const
1273     { return get_points (font, gid, path_builder_t (font, draw_helper)); }
1274 #endif
1275 
1276 #ifndef HB_NO_VAR
1277     const gvar_accelerator_t *gvar;
1278 #endif
1279     const hmtx_accelerator_t *hmtx;
1280 #ifndef HB_NO_VERTICAL
1281     const vmtx_accelerator_t *vmtx;
1282 #endif
1283 
1284     private:
1285     bool short_offset;
1286     unsigned int num_glyphs;
1287     hb_blob_ptr_t<loca> loca_table;
1288     hb_blob_ptr_t<glyf> glyf_table;
1289   };
1290 
1291   struct SubsetGlyph
1292   {
1293     hb_codepoint_t new_gid;
1294     hb_codepoint_t old_gid;
1295     Glyph source_glyph;
1296     hb_bytes_t dest_start;  /* region of source_glyph to copy first */
1297     hb_bytes_t dest_end;    /* region of source_glyph to copy second */
1298 
serializeOT::glyf::SubsetGlyph1299     bool serialize (hb_serialize_context_t *c,
1300                     bool use_short_loca,
1301 		    const hb_subset_plan_t *plan) const
1302     {
1303       TRACE_SERIALIZE (this);
1304 
1305       hb_bytes_t dest_glyph = dest_start.copy (c);
1306       dest_glyph = hb_bytes_t (&dest_glyph, dest_glyph.length + dest_end.copy (c).length);
1307       unsigned int pad_length = use_short_loca ? padding () : 0;
1308       DEBUG_MSG (SUBSET, nullptr, "serialize %d byte glyph, width %d pad %d", dest_glyph.length, dest_glyph.length + pad_length, pad_length);
1309 
1310       HBUINT8 pad;
1311       pad = 0;
1312       while (pad_length > 0)
1313       {
1314 	c->embed (pad);
1315 	pad_length--;
1316       }
1317 
1318       if (unlikely (!dest_glyph.length)) return_trace (true);
1319 
1320       /* update components gids */
1321       for (auto &_ : Glyph (dest_glyph).get_composite_iterator ())
1322       {
1323 	hb_codepoint_t new_gid;
1324 	if (plan->new_gid_for_old_gid (_.get_glyph_index (), &new_gid))
1325 	  const_cast<CompositeGlyphChain &> (_).set_glyph_index (new_gid);
1326       }
1327 
1328       if (plan->flags & HB_SUBSET_FLAGS_NO_HINTING)
1329         Glyph (dest_glyph).drop_hints ();
1330 
1331       if (plan->flags & HB_SUBSET_FLAGS_SET_OVERLAPS_FLAG)
1332         Glyph (dest_glyph).set_overlaps_flag ();
1333 
1334       return_trace (true);
1335     }
1336 
drop_hints_bytesOT::glyf::SubsetGlyph1337     void drop_hints_bytes ()
1338     { source_glyph.drop_hints_bytes (dest_start, dest_end); }
1339 
lengthOT::glyf::SubsetGlyph1340     unsigned int      length () const { return dest_start.length + dest_end.length; }
1341     /* pad to 2 to ensure 2-byte loca will be ok */
paddingOT::glyf::SubsetGlyph1342     unsigned int     padding () const { return length () % 2; }
padded_sizeOT::glyf::SubsetGlyph1343     unsigned int padded_size () const { return length () + padding (); }
1344   };
1345 
1346   protected:
1347   UnsizedArrayOf<HBUINT8>
1348 		dataZ;	/* Glyphs data. */
1349   public:
1350   DEFINE_SIZE_MIN (0);	/* In reality, this is UNBOUNDED() type; but since we always
1351 			 * check the size externally, allow Null() object of it by
1352 			 * defining it _MIN instead. */
1353 };
1354 
1355 struct glyf_accelerator_t : glyf::accelerator_t {
glyf_accelerator_tOT::glyf_accelerator_t1356   glyf_accelerator_t (hb_face_t *face) : glyf::accelerator_t (face) {}
1357 };
1358 
1359 
1360 } /* namespace OT */
1361 
1362 
1363 #endif /* HB_OT_GLYF_TABLE_HH */
1364