Imported Upstream version 2.4.0
[platform/upstream/harfbuzz.git] / src / hb-subset-cff1.cc
1 /*
2  * Copyright © 2018 Adobe 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  * Adobe Author(s): Michiharu Ariza
25  */
26
27 #include "hb-open-type.hh"
28 #include "hb-ot-cff1-table.hh"
29 #include "hb-set.h"
30 #include "hb-subset-cff1.hh"
31 #include "hb-subset-plan.hh"
32 #include "hb-subset-cff-common.hh"
33 #include "hb-cff1-interp-cs.hh"
34
35 using namespace CFF;
36
37 struct remap_sid_t : remap_t
38 {
39   unsigned int add (unsigned int sid)
40   {
41     if ((sid != CFF_UNDEF_SID) && !is_std_std (sid))
42       return offset_sid (remap_t::add (unoffset_sid (sid)));
43     else
44       return sid;
45   }
46
47   unsigned int operator[] (unsigned int sid) const
48   {
49     if (is_std_std (sid) || (sid == CFF_UNDEF_SID))
50       return sid;
51     else
52       return offset_sid (remap_t::operator [] (unoffset_sid (sid)));
53   }
54
55   static const unsigned int num_std_strings = 391;
56
57   static bool is_std_std (unsigned int sid) { return sid < num_std_strings; }
58   static unsigned int offset_sid (unsigned int sid) { return sid + num_std_strings; }
59   static unsigned int unoffset_sid (unsigned int sid) { return sid - num_std_strings; }
60 };
61
62 struct cff1_sub_table_offsets_t : cff_sub_table_offsets_t
63 {
64   cff1_sub_table_offsets_t ()
65     : cff_sub_table_offsets_t (),
66       nameIndexOffset (0),
67       encodingOffset (0)
68   {
69     stringIndexInfo.init ();
70     charsetInfo.init ();
71     privateDictInfo.init ();
72   }
73
74   unsigned int  nameIndexOffset;
75   table_info_t  stringIndexInfo;
76   unsigned int  encodingOffset;
77   table_info_t  charsetInfo;
78   table_info_t  privateDictInfo;
79 };
80
81 /* a copy of a parsed out cff1_top_dict_values_t augmented with additional operators */
82 struct cff1_top_dict_values_mod_t : cff1_top_dict_values_t
83 {
84   void init (const cff1_top_dict_values_t *base_= &Null(cff1_top_dict_values_t))
85   {
86     SUPER::init ();
87     base = base_;
88   }
89
90   void fini () { SUPER::fini (); }
91
92   unsigned get_count () const { return base->get_count () + SUPER::get_count (); }
93   const cff1_top_dict_val_t &get_value (unsigned int i) const
94   {
95     if (i < base->get_count ())
96       return (*base)[i];
97     else
98       return SUPER::values[i - base->get_count ()];
99   }
100   const cff1_top_dict_val_t &operator [] (unsigned int i) const { return get_value (i); }
101
102   void reassignSIDs (const remap_sid_t& sidmap)
103   {
104     for (unsigned int i = 0; i < name_dict_values_t::ValCount; i++)
105       nameSIDs[i] = sidmap[base->nameSIDs[i]];
106   }
107
108   protected:
109   typedef cff1_top_dict_values_t SUPER;
110   const cff1_top_dict_values_t *base;
111 };
112
113 struct top_dict_modifiers_t
114 {
115   top_dict_modifiers_t (const cff1_sub_table_offsets_t &offsets_,
116                            const unsigned int (&nameSIDs_)[name_dict_values_t::ValCount])
117     : offsets (offsets_),
118       nameSIDs (nameSIDs_)
119   {}
120
121   const cff1_sub_table_offsets_t &offsets;
122   const unsigned int    (&nameSIDs)[name_dict_values_t::ValCount];
123 };
124
125 struct cff1_top_dict_op_serializer_t : cff_top_dict_op_serializer_t<cff1_top_dict_val_t>
126 {
127   bool serialize (hb_serialize_context_t *c,
128                   const cff1_top_dict_val_t &opstr,
129                   const top_dict_modifiers_t &mod) const
130   {
131     TRACE_SERIALIZE (this);
132
133     op_code_t op = opstr.op;
134     switch (op)
135     {
136       case OpCode_charset:
137         return_trace (FontDict::serialize_offset4_op(c, op, mod.offsets.charsetInfo.offset));
138
139       case OpCode_Encoding:
140         return_trace (FontDict::serialize_offset4_op(c, op, mod.offsets.encodingOffset));
141
142       case OpCode_Private:
143         {
144           if (unlikely (!UnsizedByteStr::serialize_int2 (c, mod.offsets.privateDictInfo.size)))
145             return_trace (false);
146           if (unlikely (!UnsizedByteStr::serialize_int4 (c, mod.offsets.privateDictInfo.offset)))
147             return_trace (false);
148           HBUINT8 *p = c->allocate_size<HBUINT8> (1);
149           if (unlikely (p == nullptr)) return_trace (false);
150           p->set (OpCode_Private);
151         }
152         break;
153
154       case OpCode_version:
155       case OpCode_Notice:
156       case OpCode_Copyright:
157       case OpCode_FullName:
158       case OpCode_FamilyName:
159       case OpCode_Weight:
160       case OpCode_PostScript:
161       case OpCode_BaseFontName:
162       case OpCode_FontName:
163         return_trace (FontDict::serialize_offset2_op(c, op, mod.nameSIDs[name_dict_values_t::name_op_to_index (op)]));
164
165       case OpCode_ROS:
166         {
167           /* for registry & ordering, reassigned SIDs are serialized
168            * for supplement, the original byte string is copied along with the op code */
169           op_str_t supp_op;
170           supp_op.op = op;
171           if ( unlikely (!(opstr.str.length >= opstr.last_arg_offset + 3)))
172             return_trace (false);
173           supp_op.str = byte_str_t (&opstr.str + opstr.last_arg_offset, opstr.str.length - opstr.last_arg_offset);
174           return_trace (UnsizedByteStr::serialize_int2 (c, mod.nameSIDs[name_dict_values_t::registry]) &&
175                         UnsizedByteStr::serialize_int2 (c, mod.nameSIDs[name_dict_values_t::ordering]) &&
176                         copy_opstr (c, supp_op));
177         }
178       default:
179         return_trace (cff_top_dict_op_serializer_t<cff1_top_dict_val_t>::serialize (c, opstr, mod.offsets));
180     }
181     return_trace (true);
182   }
183
184   unsigned int calculate_serialized_size (const cff1_top_dict_val_t &opstr) const
185   {
186     op_code_t op = opstr.op;
187     switch (op)
188     {
189       case OpCode_charset:
190       case OpCode_Encoding:
191         return OpCode_Size (OpCode_longintdict) + 4 + OpCode_Size (op);
192
193       case OpCode_Private:
194         return OpCode_Size (OpCode_longintdict) + 4 + OpCode_Size (OpCode_shortint) + 2 + OpCode_Size (OpCode_Private);
195
196       case OpCode_version:
197       case OpCode_Notice:
198       case OpCode_Copyright:
199       case OpCode_FullName:
200       case OpCode_FamilyName:
201       case OpCode_Weight:
202       case OpCode_PostScript:
203       case OpCode_BaseFontName:
204       case OpCode_FontName:
205         return OpCode_Size (OpCode_shortint) + 2 + OpCode_Size (op);
206
207       case OpCode_ROS:
208         return ((OpCode_Size (OpCode_shortint) + 2) * 2) + (opstr.str.length - opstr.last_arg_offset)/* supplement + op */;
209
210       default:
211         return cff_top_dict_op_serializer_t<cff1_top_dict_val_t>::calculate_serialized_size (opstr);
212     }
213   }
214 };
215
216 struct font_dict_values_mod_t
217 {
218   void init (const cff1_font_dict_values_t *base_,
219              unsigned int fontName_,
220              const table_info_t &privateDictInfo_)
221   {
222     base = base_;
223     fontName = fontName_;
224     privateDictInfo = privateDictInfo_;
225   }
226
227   unsigned get_count () const { return base->get_count (); }
228
229   const op_str_t &operator [] (unsigned int i) const { return (*base)[i]; }
230
231   const cff1_font_dict_values_t    *base;
232   table_info_t             privateDictInfo;
233   unsigned int          fontName;
234 };
235
236 struct cff1_font_dict_op_serializer_t : cff_font_dict_op_serializer_t
237 {
238   bool serialize (hb_serialize_context_t *c,
239                   const op_str_t &opstr,
240                   const font_dict_values_mod_t &mod) const
241   {
242     TRACE_SERIALIZE (this);
243
244     if (opstr.op == OpCode_FontName)
245       return_trace (FontDict::serialize_uint2_op (c, opstr.op, mod.fontName));
246     else
247       return_trace (SUPER::serialize (c, opstr, mod.privateDictInfo));
248   }
249
250   unsigned int calculate_serialized_size (const op_str_t &opstr) const
251   {
252     if (opstr.op == OpCode_FontName)
253       return OpCode_Size (OpCode_shortint) + 2 + OpCode_Size (OpCode_FontName);
254     else
255       return SUPER::calculate_serialized_size (opstr);
256   }
257
258   private:
259   typedef cff_font_dict_op_serializer_t SUPER;
260 };
261
262 struct cff1_cs_opset_flatten_t : cff1_cs_opset_t<cff1_cs_opset_flatten_t, flatten_param_t>
263 {
264   static void flush_args_and_op (op_code_t op, cff1_cs_interp_env_t &env, flatten_param_t& param)
265   {
266     if (env.arg_start > 0)
267       flush_width (env, param);
268
269     switch (op)
270     {
271       case OpCode_hstem:
272       case OpCode_hstemhm:
273       case OpCode_vstem:
274       case OpCode_vstemhm:
275       case OpCode_hintmask:
276       case OpCode_cntrmask:
277       case OpCode_dotsection:
278         if (param.drop_hints)
279         {
280           env.clear_args ();
281           return;
282         }
283         HB_FALLTHROUGH;
284
285       default:
286         SUPER::flush_args_and_op (op, env, param);
287         break;
288     }
289   }
290   static void flush_args (cff1_cs_interp_env_t &env, flatten_param_t& param)
291   {
292     str_encoder_t  encoder (param.flatStr);
293     for (unsigned int i = env.arg_start; i < env.argStack.get_count (); i++)
294       encoder.encode_num (env.eval_arg (i));
295     SUPER::flush_args (env, param);
296   }
297
298   static void flush_op (op_code_t op, cff1_cs_interp_env_t &env, flatten_param_t& param)
299   {
300     str_encoder_t  encoder (param.flatStr);
301     encoder.encode_op (op);
302   }
303
304   static void flush_width (cff1_cs_interp_env_t &env, flatten_param_t& param)
305   {
306     assert (env.has_width);
307     str_encoder_t  encoder (param.flatStr);
308     encoder.encode_num (env.width);
309   }
310
311   static void flush_hintmask (op_code_t op, cff1_cs_interp_env_t &env, flatten_param_t& param)
312   {
313     SUPER::flush_hintmask (op, env, param);
314     if (!param.drop_hints)
315     {
316       str_encoder_t  encoder (param.flatStr);
317       for (unsigned int i = 0; i < env.hintmask_size; i++)
318         encoder.encode_byte (env.str_ref[i]);
319     }
320   }
321
322   private:
323   typedef cff1_cs_opset_t<cff1_cs_opset_flatten_t, flatten_param_t> SUPER;
324 };
325
326 struct range_list_t : hb_vector_t<code_pair_t>
327 {
328   /* replace the first glyph ID in the "glyph" field each range with a nLeft value */
329   bool finalize (unsigned int last_glyph)
330   {
331     bool  two_byte = false;
332     for (unsigned int i = (*this).length; i > 0; i--)
333     {
334       code_pair_t &pair = (*this)[i - 1];
335       unsigned int  nLeft = last_glyph - pair.glyph - 1;
336       if (nLeft >= 0x100)
337         two_byte = true;
338       last_glyph = pair.glyph;
339       pair.glyph = nLeft;
340     }
341     return two_byte;
342   }
343 };
344
345 struct cff1_cs_opset_subr_subset_t : cff1_cs_opset_t<cff1_cs_opset_subr_subset_t, subr_subset_param_t>
346 {
347   static void process_op (op_code_t op, cff1_cs_interp_env_t &env, subr_subset_param_t& param)
348   {
349     switch (op) {
350
351       case OpCode_return:
352         param.current_parsed_str->add_op (op, env.str_ref);
353         param.current_parsed_str->set_parsed ();
354         env.returnFromSubr ();
355         param.set_current_str (env, false);
356         break;
357
358       case OpCode_endchar:
359         param.current_parsed_str->add_op (op, env.str_ref);
360         param.current_parsed_str->set_parsed ();
361         SUPER::process_op (op, env, param);
362         break;
363
364       case OpCode_callsubr:
365         process_call_subr (op, CSType_LocalSubr, env, param, env.localSubrs, param.local_closure);
366         break;
367
368       case OpCode_callgsubr:
369         process_call_subr (op, CSType_GlobalSubr, env, param, env.globalSubrs, param.global_closure);
370         break;
371
372       default:
373         SUPER::process_op (op, env, param);
374         param.current_parsed_str->add_op (op, env.str_ref);
375         break;
376     }
377   }
378
379   protected:
380   static void process_call_subr (op_code_t op, cs_type_t type,
381                                  cff1_cs_interp_env_t &env, subr_subset_param_t& param,
382                                  cff1_biased_subrs_t& subrs, hb_set_t *closure)
383   {
384     byte_str_ref_t    str_ref = env.str_ref;
385     env.callSubr (subrs, type);
386     param.current_parsed_str->add_call_op (op, str_ref, env.context.subr_num);
387     hb_set_add (closure, env.context.subr_num);
388     param.set_current_str (env, true);
389   }
390
391   private:
392   typedef cff1_cs_opset_t<cff1_cs_opset_subr_subset_t, subr_subset_param_t> SUPER;
393 };
394
395 struct cff1_subr_subsetter_t : subr_subsetter_t<cff1_subr_subsetter_t, CFF1Subrs, const OT::cff1::accelerator_subset_t, cff1_cs_interp_env_t, cff1_cs_opset_subr_subset_t, OpCode_endchar>
396 {
397   cff1_subr_subsetter_t (const OT::cff1::accelerator_subset_t &acc, const hb_subset_plan_t *plan)
398     : subr_subsetter_t (acc, plan) {}
399
400   static void finalize_parsed_str (cff1_cs_interp_env_t &env, subr_subset_param_t& param, parsed_cs_str_t &charstring)
401   {
402     /* insert width at the beginning of the charstring as necessary */
403     if (env.has_width)
404       charstring.set_prefix (env.width);
405
406     /* subroutines/charstring left on the call stack are legally left unmarked
407      * unmarked when a subroutine terminates with endchar. mark them.
408      */
409     param.current_parsed_str->set_parsed ();
410     for (unsigned int i = 0; i < env.callStack.get_count (); i++)
411     {
412       parsed_cs_str_t  *parsed_str = param.get_parsed_str_for_context (env.callStack[i]);
413       if (likely (parsed_str != nullptr))
414         parsed_str->set_parsed ();
415       else
416         env.set_error ();
417     }
418   }
419 };
420
421 struct cff_subset_plan {
422   cff_subset_plan ()
423     : final_size (0),
424       offsets (),
425       orig_fdcount (0),
426       subset_fdcount (1),
427       subset_fdselect_format (0),
428       drop_hints (false),
429       desubroutinize(false)
430   {
431     topdict_sizes.init ();
432     topdict_sizes.resize (1);
433     topdict_mod.init ();
434     subset_fdselect_ranges.init ();
435     fdmap.init ();
436     subset_charstrings.init ();
437     subset_globalsubrs.init ();
438     subset_localsubrs.init ();
439     fontdicts_mod.init ();
440     subset_enc_code_ranges.init ();
441     subset_enc_supp_codes.init ();
442     subset_charset_ranges.init ();
443     sidmap.init ();
444     for (unsigned int i = 0; i < name_dict_values_t::ValCount; i++)
445       topDictModSIDs[i] = CFF_UNDEF_SID;
446   }
447
448   ~cff_subset_plan ()
449   {
450     topdict_sizes.fini ();
451     topdict_mod.fini ();
452     subset_fdselect_ranges.fini ();
453     fdmap.fini ();
454     subset_charstrings.fini_deep ();
455     subset_globalsubrs.fini_deep ();
456     subset_localsubrs.fini_deep ();
457     fontdicts_mod.fini ();
458     subset_enc_code_ranges.fini ();
459     subset_enc_supp_codes.fini ();
460     subset_charset_ranges.fini ();
461     sidmap.fini ();
462   }
463
464   unsigned int plan_subset_encoding (const OT::cff1::accelerator_subset_t &acc, hb_subset_plan_t *plan)
465   {
466     const Encoding *encoding = acc.encoding;
467     unsigned int  size0, size1, supp_size;
468     hb_codepoint_t  code, last_code = CFF_UNDEF_CODE;
469     hb_vector_t<hb_codepoint_t> supp_codes;
470
471     subset_enc_code_ranges.resize (0);
472     supp_size = 0;
473     supp_codes.init ();
474
475     subset_enc_num_codes = plan->num_output_glyphs () - 1;
476     unsigned int glyph;
477     for (glyph = 1; glyph < plan->num_output_glyphs (); glyph++)
478     {
479       hb_codepoint_t  old_glyph;
480       if (!plan->old_gid_for_new_gid (glyph, &old_glyph))
481       {
482         /* Retain the code for the old missing glyph ID */
483         old_glyph = glyph;
484       }
485       code = acc.glyph_to_code (old_glyph);
486       if (code == CFF_UNDEF_CODE)
487       {
488         subset_enc_num_codes = glyph - 1;
489         break;
490       }
491
492       if ((last_code == CFF_UNDEF_CODE) || (code != last_code + 1))
493       {
494         code_pair_t pair = { code, glyph };
495         subset_enc_code_ranges.push (pair);
496       }
497       last_code = code;
498
499       if (encoding != &Null(Encoding))
500       {
501         hb_codepoint_t  sid = acc.glyph_to_sid (old_glyph);
502         encoding->get_supplement_codes (sid, supp_codes);
503         for (unsigned int i = 0; i < supp_codes.length; i++)
504         {
505           code_pair_t pair = { supp_codes[i], sid };
506           subset_enc_supp_codes.push (pair);
507         }
508         supp_size += SuppEncoding::static_size * supp_codes.length;
509       }
510     }
511     supp_codes.fini ();
512
513     subset_enc_code_ranges.finalize (glyph);
514
515     assert (subset_enc_num_codes <= 0xFF);
516     size0 = Encoding0::min_size + HBUINT8::static_size * subset_enc_num_codes;
517     size1 = Encoding1::min_size + Encoding1_Range::static_size * subset_enc_code_ranges.length;
518
519     if (size0 < size1)
520       subset_enc_format = 0;
521     else
522       subset_enc_format = 1;
523
524     return Encoding::calculate_serialized_size (
525                         subset_enc_format,
526                         subset_enc_format? subset_enc_code_ranges.length: subset_enc_num_codes,
527                         subset_enc_supp_codes.length);
528   }
529
530   unsigned int plan_subset_charset (const OT::cff1::accelerator_subset_t &acc, hb_subset_plan_t *plan)
531   {
532     unsigned int  size0, size_ranges;
533     hb_codepoint_t  sid, last_sid = CFF_UNDEF_CODE;
534
535     subset_charset_ranges.resize (0);
536     unsigned int glyph;
537     for (glyph = 1; glyph < plan->num_output_glyphs (); glyph++)
538     {
539       hb_codepoint_t  old_glyph;
540       if (!plan->old_gid_for_new_gid (glyph, &old_glyph))
541       {
542         /* Retain the SID for the old missing glyph ID */
543         old_glyph = glyph;
544       }
545       sid = acc.glyph_to_sid (old_glyph);
546
547       if (!acc.is_CID ())
548         sid = sidmap.add (sid);
549
550       if ((last_sid == CFF_UNDEF_CODE) || (sid != last_sid + 1))
551       {
552         code_pair_t pair = { sid, glyph };
553         subset_charset_ranges.push (pair);
554       }
555       last_sid = sid;
556     }
557
558     bool two_byte = subset_charset_ranges.finalize (glyph);
559
560     size0 = Charset0::min_size + HBUINT16::static_size * (plan->num_output_glyphs () - 1);
561     if (!two_byte)
562       size_ranges = Charset1::min_size + Charset1_Range::static_size * subset_charset_ranges.length;
563     else
564       size_ranges = Charset2::min_size + Charset2_Range::static_size * subset_charset_ranges.length;
565
566     if (size0 < size_ranges)
567       subset_charset_format = 0;
568     else if (!two_byte)
569       subset_charset_format = 1;
570     else
571       subset_charset_format = 2;
572
573     return Charset::calculate_serialized_size (
574                         subset_charset_format,
575                         subset_charset_format? subset_charset_ranges.length: plan->num_output_glyphs ());
576   }
577
578   bool collect_sids_in_dicts (const OT::cff1::accelerator_subset_t &acc)
579   {
580     if (unlikely (!sidmap.reset (acc.stringIndex->count)))
581       return false;
582
583     for (unsigned int i = 0; i < name_dict_values_t::ValCount; i++)
584     {
585       unsigned int sid = acc.topDict.nameSIDs[i];
586       if (sid != CFF_UNDEF_SID)
587       {
588         (void)sidmap.add (sid);
589         topDictModSIDs[i] = sidmap[sid];
590       }
591     }
592
593     if (acc.fdArray != &Null(CFF1FDArray))
594       for (unsigned int i = 0; i < orig_fdcount; i++)
595         if (fdmap.includes (i))
596           (void)sidmap.add (acc.fontDicts[i].fontName);
597
598     return true;
599   }
600
601   bool create (const OT::cff1::accelerator_subset_t &acc,
602                hb_subset_plan_t *plan)
603   {
604     /* make sure notdef is first */
605     hb_codepoint_t old_glyph;
606     if (!plan->old_gid_for_new_gid (0, &old_glyph) || (old_glyph != 0)) return false;
607
608     final_size = 0;
609     num_glyphs = plan->num_output_glyphs ();
610     orig_fdcount = acc.fdCount;
611     drop_hints = plan->drop_hints;
612     desubroutinize = plan->desubroutinize;
613
614     /* check whether the subset renumbers any glyph IDs */
615     gid_renum = false;
616     for (hb_codepoint_t new_glyph = 0; new_glyph < plan->num_output_glyphs (); new_glyph++)
617     {
618       if (!plan->old_gid_for_new_gid(new_glyph, &old_glyph))
619         continue;
620       if (new_glyph != old_glyph) {
621         gid_renum = true;
622         break;
623       }
624     }
625
626     subset_charset = gid_renum || !acc.is_predef_charset ();
627     subset_encoding = !acc.is_CID() && !acc.is_predef_encoding ();
628
629     /* CFF header */
630     final_size += OT::cff1::static_size;
631
632     /* Name INDEX */
633     offsets.nameIndexOffset = final_size;
634     final_size += acc.nameIndex->get_size ();
635
636     /* top dict INDEX */
637     {
638       /* Add encoding/charset to a (copy of) top dict as necessary */
639       topdict_mod.init (&acc.topDict);
640       bool need_to_add_enc = (subset_encoding && !acc.topDict.has_op (OpCode_Encoding));
641       bool need_to_add_set = (subset_charset && !acc.topDict.has_op (OpCode_charset));
642       if (need_to_add_enc || need_to_add_set)
643       {
644         if (need_to_add_enc)
645           topdict_mod.add_op (OpCode_Encoding);
646         if (need_to_add_set)
647           topdict_mod.add_op (OpCode_charset);
648       }
649       offsets.topDictInfo.offset = final_size;
650       cff1_top_dict_op_serializer_t topSzr;
651       unsigned int topDictSize = TopDict::calculate_serialized_size (topdict_mod, topSzr);
652       offsets.topDictInfo.offSize = calcOffSize(topDictSize);
653       if (unlikely (offsets.topDictInfo.offSize > 4))
654         return false;
655       final_size += CFF1IndexOf<TopDict>::calculate_serialized_size<cff1_top_dict_values_mod_t>
656                                                 (offsets.topDictInfo.offSize,
657                                                  &topdict_mod, 1, topdict_sizes, topSzr);
658     }
659
660     /* Determine re-mapping of font index as fdmap among other info */
661     if (acc.fdSelect != &Null(CFF1FDSelect))
662     {
663         if (unlikely (!hb_plan_subset_cff_fdselect (plan,
664                                   orig_fdcount,
665                                   *acc.fdSelect,
666                                   subset_fdcount,
667                                   offsets.FDSelectInfo.size,
668                                   subset_fdselect_format,
669                                   subset_fdselect_ranges,
670                                   fdmap)))
671         return false;
672     }
673     else
674       fdmap.identity (1);
675
676     /* remove unused SIDs & reassign SIDs */
677     {
678       /* SIDs for name strings in dicts are added before glyph names so they fit in 16-bit int range */
679       if (unlikely (!collect_sids_in_dicts (acc)))
680         return false;
681       if (unlikely (sidmap.get_count () > 0x8000))      /* assumption: a dict won't reference that many strings */
682         return false;
683       if (subset_charset)
684         offsets.charsetInfo.size = plan_subset_charset (acc, plan);
685
686       topdict_mod.reassignSIDs (sidmap);
687     }
688
689     /* String INDEX */
690     {
691       offsets.stringIndexInfo.offset = final_size;
692       offsets.stringIndexInfo.size = acc.stringIndex->calculate_serialized_size (offsets.stringIndexInfo.offSize, sidmap);
693       final_size += offsets.stringIndexInfo.size;
694     }
695
696     if (desubroutinize)
697     {
698       /* Flatten global & local subrs */
699       subr_flattener_t<const OT::cff1::accelerator_subset_t, cff1_cs_interp_env_t, cff1_cs_opset_flatten_t, OpCode_endchar>
700                     flattener(acc, plan);
701       if (!flattener.flatten (subset_charstrings))
702         return false;
703
704       /* no global/local subroutines */
705       offsets.globalSubrsInfo.size = CFF1Subrs::calculate_serialized_size (1, 0, 0);
706     }
707     else
708     {
709       cff1_subr_subsetter_t       subr_subsetter (acc, plan);
710
711       /* Subset subrs: collect used subroutines, leaving all unused ones behind */
712       if (!subr_subsetter.subset ())
713         return false;
714
715       /* encode charstrings, global subrs, local subrs with new subroutine numbers */
716       if (!subr_subsetter.encode_charstrings (subset_charstrings))
717         return false;
718
719       if (!subr_subsetter.encode_globalsubrs (subset_globalsubrs))
720         return false;
721
722       /* global subrs */
723       unsigned int dataSize = subset_globalsubrs.total_size ();
724       offsets.globalSubrsInfo.offSize = calcOffSize (dataSize);
725       if (unlikely (offsets.globalSubrsInfo.offSize > 4))
726         return false;
727       offsets.globalSubrsInfo.size = CFF1Subrs::calculate_serialized_size (offsets.globalSubrsInfo.offSize, subset_globalsubrs.length, dataSize);
728
729       /* local subrs */
730       if (!offsets.localSubrsInfos.resize (orig_fdcount))
731         return false;
732       if (!subset_localsubrs.resize (orig_fdcount))
733         return false;
734       for (unsigned int fd = 0; fd < orig_fdcount; fd++)
735       {
736         subset_localsubrs[fd].init ();
737         offsets.localSubrsInfos[fd].init ();
738         if (fdmap.includes (fd))
739         {
740           if (!subr_subsetter.encode_localsubrs (fd, subset_localsubrs[fd]))
741             return false;
742
743           unsigned int dataSize = subset_localsubrs[fd].total_size ();
744           if (dataSize > 0)
745           {
746             offsets.localSubrsInfos[fd].offset = final_size;
747             offsets.localSubrsInfos[fd].offSize = calcOffSize (dataSize);
748             if (unlikely (offsets.localSubrsInfos[fd].offSize > 4))
749               return false;
750             offsets.localSubrsInfos[fd].size = CFF1Subrs::calculate_serialized_size (offsets.localSubrsInfos[fd].offSize, subset_localsubrs[fd].length, dataSize);
751           }
752         }
753       }
754     }
755
756     /* global subrs */
757     offsets.globalSubrsInfo.offset = final_size;
758     final_size += offsets.globalSubrsInfo.size;
759
760     /* Encoding */
761     if (!subset_encoding)
762       offsets.encodingOffset = acc.topDict.EncodingOffset;
763     else
764     {
765       offsets.encodingOffset = final_size;
766       final_size += plan_subset_encoding (acc, plan);
767     }
768
769     /* Charset */
770     if (!subset_charset && acc.is_predef_charset ())
771       offsets.charsetInfo.offset = acc.topDict.CharsetOffset;
772     else
773       offsets.charsetInfo.offset = final_size;
774     final_size += offsets.charsetInfo.size;
775
776     /* FDSelect */
777     if (acc.fdSelect != &Null(CFF1FDSelect))
778     {
779       offsets.FDSelectInfo.offset = final_size;
780       final_size += offsets.FDSelectInfo.size;
781     }
782
783     /* FDArray (FDIndex) */
784     if (acc.fdArray != &Null(CFF1FDArray)) {
785       offsets.FDArrayInfo.offset = final_size;
786       cff1_font_dict_op_serializer_t fontSzr;
787       unsigned int dictsSize = 0;
788       for (unsigned int i = 0; i < acc.fontDicts.length; i++)
789         if (fdmap.includes (i))
790           dictsSize += FontDict::calculate_serialized_size (acc.fontDicts[i], fontSzr);
791
792       offsets.FDArrayInfo.offSize = calcOffSize (dictsSize);
793       if (unlikely (offsets.FDArrayInfo.offSize > 4))
794         return false;
795       final_size += CFF1Index::calculate_serialized_size (offsets.FDArrayInfo.offSize, subset_fdcount, dictsSize);
796     }
797
798     /* CharStrings */
799     {
800       offsets.charStringsInfo.offset = final_size;
801       unsigned int dataSize = subset_charstrings.total_size ();
802       offsets.charStringsInfo.offSize = calcOffSize (dataSize);
803       if (unlikely (offsets.charStringsInfo.offSize > 4))
804         return false;
805       final_size += CFF1CharStrings::calculate_serialized_size (offsets.charStringsInfo.offSize, plan->num_output_glyphs (), dataSize);
806     }
807
808     /* private dicts & local subrs */
809     offsets.privateDictInfo.offset = final_size;
810     for (unsigned int i = 0; i < orig_fdcount; i++)
811     {
812       if (fdmap.includes (i))
813       {
814         bool  has_localsubrs = offsets.localSubrsInfos[i].size > 0;
815         cff_private_dict_op_serializer_t privSzr (desubroutinize, plan->drop_hints);
816         unsigned int  priv_size = PrivateDict::calculate_serialized_size (acc.privateDicts[i], privSzr, has_localsubrs);
817         table_info_t  privInfo = { final_size, priv_size, 0 };
818         font_dict_values_mod_t fontdict_mod;
819         if (!acc.is_CID ())
820           fontdict_mod.init ( &Null(cff1_font_dict_values_t), CFF_UNDEF_SID, privInfo );
821         else
822           fontdict_mod.init ( &acc.fontDicts[i], sidmap[acc.fontDicts[i].fontName], privInfo );
823         fontdicts_mod.push (fontdict_mod);
824         final_size += privInfo.size;
825
826         if (!plan->desubroutinize && has_localsubrs)
827         {
828           offsets.localSubrsInfos[i].offset = final_size;
829           final_size += offsets.localSubrsInfos[i].size;
830         }
831       }
832     }
833
834     if (!acc.is_CID ())
835       offsets.privateDictInfo = fontdicts_mod[0].privateDictInfo;
836
837     return ((subset_charstrings.length == plan->num_output_glyphs ())
838            && (fontdicts_mod.length == subset_fdcount));
839   }
840
841   unsigned int get_final_size () const  { return final_size; }
842
843   unsigned int        final_size;
844   hb_vector_t<unsigned int>     topdict_sizes;
845   cff1_top_dict_values_mod_t    topdict_mod;
846   cff1_sub_table_offsets_t      offsets;
847
848   unsigned int    num_glyphs;
849   unsigned int    orig_fdcount;
850   unsigned int    subset_fdcount;
851   unsigned int    subset_fdselect_format;
852   hb_vector_t<code_pair_t>   subset_fdselect_ranges;
853
854   /* font dict index remap table from fullset FDArray to subset FDArray.
855    * set to CFF_UNDEF_CODE if excluded from subset */
856   remap_t   fdmap;
857
858   str_buff_vec_t                subset_charstrings;
859   str_buff_vec_t                subset_globalsubrs;
860   hb_vector_t<str_buff_vec_t>   subset_localsubrs;
861   hb_vector_t<font_dict_values_mod_t>  fontdicts_mod;
862
863   bool          drop_hints;
864
865   bool          gid_renum;
866   bool          subset_encoding;
867   uint8_t       subset_enc_format;
868   unsigned int  subset_enc_num_codes;
869   range_list_t  subset_enc_code_ranges;
870   hb_vector_t<code_pair_t>  subset_enc_supp_codes;
871
872   uint8_t       subset_charset_format;
873   range_list_t  subset_charset_ranges;
874   bool          subset_charset;
875
876   remap_sid_t   sidmap;
877   unsigned int  topDictModSIDs[name_dict_values_t::ValCount];
878
879   bool          desubroutinize;
880 };
881
882 static inline bool _write_cff1 (const cff_subset_plan &plan,
883                                 const OT::cff1::accelerator_subset_t  &acc,
884                                 unsigned int num_glyphs,
885                                 unsigned int dest_sz,
886                                 void *dest)
887 {
888   hb_serialize_context_t c (dest, dest_sz);
889
890   OT::cff1 *cff = c.start_serialize<OT::cff1> ();
891   if (unlikely (!c.extend_min (*cff)))
892     return false;
893
894   /* header */
895   cff->version.major.set (0x01);
896   cff->version.minor.set (0x00);
897   cff->nameIndex.set (cff->min_size);
898   cff->offSize.set (4); /* unused? */
899
900   /* name INDEX */
901   {
902     assert (cff->nameIndex == (unsigned) (c.head - c.start));
903     CFF1NameIndex *dest = c.start_embed<CFF1NameIndex> ();
904     if (unlikely (dest == nullptr)) return false;
905     if (unlikely (!dest->serialize (&c, *acc.nameIndex)))
906     {
907       DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF name INDEX");
908       return false;
909     }
910   }
911
912   /* top dict INDEX */
913   {
914     assert (plan.offsets.topDictInfo.offset == (unsigned) (c.head - c.start));
915     CFF1IndexOf<TopDict> *dest = c.start_embed< CFF1IndexOf<TopDict> > ();
916     if (dest == nullptr) return false;
917     cff1_top_dict_op_serializer_t topSzr;
918     top_dict_modifiers_t  modifier (plan.offsets, plan.topDictModSIDs);
919     if (unlikely (!dest->serialize (&c, plan.offsets.topDictInfo.offSize,
920                                     &plan.topdict_mod, 1,
921                                     plan.topdict_sizes, topSzr, modifier)))
922     {
923       DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF top dict");
924       return false;
925     }
926   }
927
928   /* String INDEX */
929   {
930     assert (plan.offsets.stringIndexInfo.offset == (unsigned) (c.head - c.start));
931     CFF1StringIndex *dest = c.start_embed<CFF1StringIndex> ();
932     if (unlikely (dest == nullptr)) return false;
933     if (unlikely (!dest->serialize (&c, *acc.stringIndex, plan.offsets.stringIndexInfo.offSize, plan.sidmap)))
934     {
935       DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF string INDEX");
936       return false;
937     }
938   }
939
940   /* global subrs */
941   {
942     assert (plan.offsets.globalSubrsInfo.offset != 0);
943     assert (plan.offsets.globalSubrsInfo.offset == (unsigned) (c.head - c.start));
944
945     CFF1Subrs *dest = c.start_embed <CFF1Subrs> ();
946     if (unlikely (dest == nullptr)) return false;
947     if (unlikely (!dest->serialize (&c, plan.offsets.globalSubrsInfo.offSize, plan.subset_globalsubrs)))
948     {
949       DEBUG_MSG (SUBSET, nullptr, "failed to serialize global subroutines");
950       return false;
951     }
952   }
953
954   /* Encoding */
955   if (plan.subset_encoding)
956   {
957     assert (plan.offsets.encodingOffset == (unsigned) (c.head - c.start));
958     Encoding *dest = c.start_embed<Encoding> ();
959     if (unlikely (dest == nullptr)) return false;
960     if (unlikely (!dest->serialize (&c,
961                                     plan.subset_enc_format,
962                                     plan.subset_enc_num_codes,
963                                     plan.subset_enc_code_ranges,
964                                     plan.subset_enc_supp_codes)))
965     {
966       DEBUG_MSG (SUBSET, nullptr, "failed to serialize Encoding");
967       return false;
968     }
969   }
970
971   /* Charset */
972   if (plan.subset_charset)
973   {
974     assert (plan.offsets.charsetInfo.offset == (unsigned) (c.head - c.start));
975     Charset *dest = c.start_embed<Charset> ();
976     if (unlikely (dest == nullptr)) return false;
977     if (unlikely (!dest->serialize (&c,
978                                     plan.subset_charset_format,
979                                     plan.num_glyphs,
980                                     plan.subset_charset_ranges)))
981     {
982       DEBUG_MSG (SUBSET, nullptr, "failed to serialize Charset");
983       return false;
984     }
985   }
986
987   /* FDSelect */
988   if (acc.fdSelect != &Null(CFF1FDSelect))
989   {
990     assert (plan.offsets.FDSelectInfo.offset == (unsigned) (c.head - c.start));
991
992     if (unlikely (!hb_serialize_cff_fdselect (&c, num_glyphs, *acc.fdSelect, acc.fdCount,
993                                               plan.subset_fdselect_format, plan.offsets.FDSelectInfo.size,
994                                               plan.subset_fdselect_ranges)))
995     {
996       DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF subset FDSelect");
997       return false;
998     }
999   }
1000
1001   /* FDArray (FD Index) */
1002   if (acc.fdArray != &Null(CFF1FDArray))
1003   {
1004     assert (plan.offsets.FDArrayInfo.offset == (unsigned) (c.head - c.start));
1005     CFF1FDArray  *fda = c.start_embed<CFF1FDArray> ();
1006     if (unlikely (fda == nullptr)) return false;
1007     cff1_font_dict_op_serializer_t  fontSzr;
1008     if (unlikely (!fda->serialize (&c, plan.offsets.FDArrayInfo.offSize,
1009                                    plan.fontdicts_mod,
1010                                    fontSzr)))
1011     {
1012       DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF FDArray");
1013       return false;
1014     }
1015   }
1016
1017   /* CharStrings */
1018   {
1019     assert (plan.offsets.charStringsInfo.offset == (unsigned) (c.head - c.start));
1020     CFF1CharStrings  *cs = c.start_embed<CFF1CharStrings> ();
1021     if (unlikely (cs == nullptr)) return false;
1022     if (unlikely (!cs->serialize (&c, plan.offsets.charStringsInfo.offSize, plan.subset_charstrings)))
1023     {
1024       DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF CharStrings");
1025       return false;
1026     }
1027   }
1028
1029   /* private dicts & local subrs */
1030   assert (plan.offsets.privateDictInfo.offset == (unsigned) (c.head - c.start));
1031   for (unsigned int i = 0; i < acc.privateDicts.length; i++)
1032   {
1033     if (plan.fdmap.includes (i))
1034     {
1035       PrivateDict  *pd = c.start_embed<PrivateDict> ();
1036       if (unlikely (pd == nullptr)) return false;
1037       unsigned int priv_size = plan.fontdicts_mod[plan.fdmap[i]].privateDictInfo.size;
1038       bool result;
1039       cff_private_dict_op_serializer_t privSzr (plan.desubroutinize, plan.drop_hints);
1040       /* N.B. local subrs immediately follows its corresponding private dict. i.e., subr offset == private dict size */
1041       unsigned int  subroffset = (plan.offsets.localSubrsInfos[i].size > 0)? priv_size: 0;
1042       result = pd->serialize (&c, acc.privateDicts[i], privSzr, subroffset);
1043       if (unlikely (!result))
1044       {
1045         DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF Private Dict[%d]", i);
1046         return false;
1047       }
1048       if (plan.offsets.localSubrsInfos[i].size > 0)
1049       {
1050         CFF1Subrs *dest = c.start_embed <CFF1Subrs> ();
1051         if (unlikely (dest == nullptr)) return false;
1052         if (unlikely (!dest->serialize (&c, plan.offsets.localSubrsInfos[i].offSize, plan.subset_localsubrs[i])))
1053         {
1054           DEBUG_MSG (SUBSET, nullptr, "failed to serialize local subroutines");
1055           return false;
1056         }
1057       }
1058     }
1059   }
1060
1061   assert (c.head == c.end);
1062   c.end_serialize ();
1063
1064   return true;
1065 }
1066
1067 static bool
1068 _hb_subset_cff1 (const OT::cff1::accelerator_subset_t  &acc,
1069                 const char              *data,
1070                 hb_subset_plan_t        *plan,
1071                 hb_blob_t               **prime /* OUT */)
1072 {
1073   cff_subset_plan cff_plan;
1074
1075   if (unlikely (!cff_plan.create (acc, plan)))
1076   {
1077     DEBUG_MSG(SUBSET, nullptr, "Failed to generate a cff subsetting plan.");
1078     return false;
1079   }
1080
1081   unsigned int  cff_prime_size = cff_plan.get_final_size ();
1082   char *cff_prime_data = (char *) calloc (1, cff_prime_size);
1083
1084   if (unlikely (!_write_cff1 (cff_plan, acc, plan->num_output_glyphs (),
1085                               cff_prime_size, cff_prime_data))) {
1086     DEBUG_MSG(SUBSET, nullptr, "Failed to write a subset cff.");
1087     free (cff_prime_data);
1088     return false;
1089   }
1090
1091   *prime = hb_blob_create (cff_prime_data,
1092                            cff_prime_size,
1093                            HB_MEMORY_MODE_READONLY,
1094                            cff_prime_data,
1095                            free);
1096   return true;
1097 }
1098
1099 /**
1100  * hb_subset_cff1:
1101  * Subsets the CFF table according to a provided plan.
1102  *
1103  * Return value: subsetted cff table.
1104  **/
1105 bool
1106 hb_subset_cff1 (hb_subset_plan_t *plan,
1107                 hb_blob_t       **prime /* OUT */)
1108 {
1109   hb_blob_t *cff_blob = hb_sanitize_context_t().reference_table<CFF::cff1> (plan->source);
1110   const char *data = hb_blob_get_data(cff_blob, nullptr);
1111
1112   OT::cff1::accelerator_subset_t acc;
1113   acc.init(plan->source);
1114   bool result = likely (acc.is_valid ()) &&
1115                         _hb_subset_cff1 (acc, data, plan, prime);
1116   hb_blob_destroy (cff_blob);
1117   acc.fini ();
1118
1119   return result;
1120 }