hb-subset-cff1.cc 22.9 KB
Newer Older
M
Michiharu Ariza 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/*
 * Copyright © 2018 Adobe Systems Incorporated.
 *
 *  This is part of HarfBuzz, a text shaping library.
 *
 * Permission is hereby granted, without written agreement and without
 * license or royalty fees, to use, copy, modify, and distribute this
 * software and its documentation for any purpose, provided that the
 * above copyright notice and the following two paragraphs appear in
 * all copies of this software.
 *
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
 * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
 * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 *
 * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
 * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 *
 * Adobe Author(s): Michiharu Ariza
 */

#include "hb-open-type-private.hh"
28
#include "hb-ot-cff1-table.hh"
M
Michiharu Ariza 已提交
29
#include "hb-set.h"
30
#include "hb-subset-cff1.hh"
M
Michiharu Ariza 已提交
31 32
#include "hb-subset-plan.hh"
#include "hb-subset-cff-common-private.hh"
33
#include "hb-cff1-interp-cs.hh"
M
Michiharu Ariza 已提交
34 35 36

using namespace CFF;

37 38
struct CFF1SubTableOffsets {
  inline CFF1SubTableOffsets (void)
M
Michiharu Ariza 已提交
39 40
  {
    memset (this, 0, sizeof(*this));
M
Michiharu Ariza 已提交
41 42 43
    localSubrsInfos.init ();
  }

44
  inline ~CFF1SubTableOffsets (void)
M
Michiharu Ariza 已提交
45 46
  {
    localSubrsInfos.fini ();
M
Michiharu Ariza 已提交
47 48 49
  }

  unsigned int  nameIndexOffset;
M
Michiharu Ariza 已提交
50
  TableInfo     topDictInfo;
M
Michiharu Ariza 已提交
51
  unsigned int  stringIndexOffset;
M
Michiharu Ariza 已提交
52
  TableInfo     globalSubrsInfo;
M
Michiharu Ariza 已提交
53 54 55
  unsigned int  encodingOffset;
  unsigned int  charsetOffset;
  TableInfo     FDSelectInfo;
M
Michiharu Ariza 已提交
56 57
  TableInfo     FDArrayInfo;
  TableInfo     charStringsInfo;
M
Michiharu Ariza 已提交
58
  TableInfo     privateDictInfo;
M
Michiharu Ariza 已提交
59
  hb_vector_t<TableInfo>  localSubrsInfos;
M
Michiharu Ariza 已提交
60 61
};

62
struct CFF1TopDict_OpSerializer : OpSerializer
M
Michiharu Ariza 已提交
63 64 65
{
  inline bool serialize (hb_serialize_context_t *c,
                         const OpStr &opstr,
66
                         const CFF1SubTableOffsets &offsets) const
M
Michiharu Ariza 已提交
67 68 69 70 71 72 73 74 75 76 77 78
  {
    TRACE_SERIALIZE (this);

    switch (opstr.op)
    {
      case OpCode_charset:
        return_trace (FontDict::serialize_offset4_op(c, opstr.op, offsets.charsetOffset));

      case OpCode_Encoding:
        return_trace (FontDict::serialize_offset4_op(c, opstr.op, offsets.encodingOffset));

      case OpCode_CharStrings:
M
Michiharu Ariza 已提交
79
        return_trace (FontDict::serialize_offset4_op(c, opstr.op, offsets.charStringsInfo.offset));
M
Michiharu Ariza 已提交
80 81

      case OpCode_FDArray:
M
Michiharu Ariza 已提交
82
        return_trace (FontDict::serialize_offset4_op(c, opstr.op, offsets.FDArrayInfo.offset));
M
Michiharu Ariza 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

      case OpCode_FDSelect:
        return_trace (FontDict::serialize_offset4_op(c, opstr.op, offsets.FDSelectInfo.offset));

      case OpCode_Private:
        {
          if (unlikely (!UnsizedByteStr::serialize_int2 (c, offsets.privateDictInfo.size)))
            return_trace (false);
          if (unlikely (!UnsizedByteStr::serialize_int4 (c, offsets.privateDictInfo.offset)))
            return_trace (false);
          HBUINT8 *p = c->allocate_size<HBUINT8> (1);
          if (unlikely (p == nullptr)) return_trace (false);
          p->set (OpCode_Private);
        }
        break;

      default:
        return_trace (copy_opstr (c, opstr));
    }
    return_trace (true);
  }

  inline unsigned int calculate_serialized_size (const OpStr &opstr) const
  {
    switch (opstr.op)
    {
      case OpCode_charset:
      case OpCode_Encoding:
      case OpCode_CharStrings:
      case OpCode_FDArray:
      case OpCode_FDSelect:
M
Michiharu Ariza 已提交
114
        return OpCode_Size (OpCode_longintdict) + 4 + OpCode_Size (opstr.op);
M
Michiharu Ariza 已提交
115 116
    
      case OpCode_Private:
M
Michiharu Ariza 已提交
117
        return OpCode_Size (OpCode_longintdict) + 4 + OpCode_Size (OpCode_shortint) + 2 + OpCode_Size (OpCode_Private);
M
Michiharu Ariza 已提交
118 119 120 121 122 123 124
    
      default:
        return opstr.str.len;
    }
  }
};

125
struct CFF1FontDict_OpSerializer : OpSerializer
M
Michiharu Ariza 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
{
  inline bool serialize (hb_serialize_context_t *c,
                         const OpStr &opstr,
                         const TableInfo &privateDictInfo) const
  {
    TRACE_SERIALIZE (this);

    if (opstr.op == OpCode_Private)
    {
      /* serialize the private dict size as a 2-byte integer */
      if (unlikely (!UnsizedByteStr::serialize_int2 (c, privateDictInfo.size)))
        return_trace (false);

      /* serialize the private dict offset as a 4-byte integer */
      if (unlikely (!UnsizedByteStr::serialize_int4 (c, privateDictInfo.offset)))
        return_trace (false);

      /* serialize the opcode */
      HBUINT8 *p = c->allocate_size<HBUINT8> (1);
      if (unlikely (p == nullptr)) return_trace (false);
      p->set (OpCode_Private);

      return_trace (true);
    }
    else
    {
      HBUINT8 *d = c->allocate_size<HBUINT8> (opstr.str.len);
      if (unlikely (d == nullptr)) return_trace (false);
      memcpy (d, &opstr.str.str[0], opstr.str.len);
    }
    return_trace (true);
  }

  inline unsigned int calculate_serialized_size (const OpStr &opstr) const
  {
    if (opstr.op == OpCode_Private)
M
Michiharu Ariza 已提交
162
      return OpCode_Size (OpCode_longintdict) + 4 + OpCode_Size (OpCode_shortint) + 2 + OpCode_Size (OpCode_Private);
M
Michiharu Ariza 已提交
163 164 165 166 167
    else
      return opstr.str.len;
  }
};

168
struct CFF1PrivateDict_OpSerializer : OpSerializer
M
Michiharu Ariza 已提交
169
{
M
Michiharu Ariza 已提交
170 171 172
  inline CFF1PrivateDict_OpSerializer (bool drop_hints_=false, bool flatten_subrs_=false)
    : drop_hints (drop_hints_), flatten_subrs (flatten_subrs_) {}

M
Michiharu Ariza 已提交
173 174 175 176 177 178
  inline bool serialize (hb_serialize_context_t *c,
                         const OpStr &opstr,
                         const unsigned int subrsOffset) const
  {
    TRACE_SERIALIZE (this);

M
Michiharu Ariza 已提交
179 180
    if (drop_hints && DictOpSet::is_hint_op (opstr.op))
      return true;
M
Michiharu Ariza 已提交
181
    if (opstr.op == OpCode_Subrs)
M
Michiharu Ariza 已提交
182 183 184 185 186 187
    {
      if (flatten_subrs)
        return_trace (true);
      else
        return_trace (FontDict::serialize_offset2_op(c, OpCode_Subrs, subrsOffset));
    }
M
Michiharu Ariza 已提交
188 189 190 191 192 193
    else
      return_trace (copy_opstr (c, opstr));
  }

  inline unsigned int calculate_serialized_size (const OpStr &opstr) const
  {
M
Michiharu Ariza 已提交
194 195
    if (drop_hints && DictOpSet::is_hint_op (opstr.op))
      return 0;
M
Michiharu Ariza 已提交
196
    if (opstr.op == OpCode_Subrs)
M
Michiharu Ariza 已提交
197 198 199 200 201 202
    {
      if (flatten_subrs)
        return 0;
      else
        return OpCode_Size (OpCode_shortint) + 2 + OpCode_Size (OpCode_Subrs);
    }
M
Michiharu Ariza 已提交
203 204 205
    else
      return opstr.str.len;
  }
M
Michiharu Ariza 已提交
206 207 208 209

  protected:
  const bool  drop_hints;
  const bool  flatten_subrs;
M
Michiharu Ariza 已提交
210 211
};

M
Michiharu Ariza 已提交
212
struct CFF1CSOpSet_Flatten : CFF1CSOpSet<CFF1CSOpSet_Flatten, ByteStrBuff>
213
{
M
Michiharu Ariza 已提交
214
  static inline bool process_op (OpCode op, CFF1CSInterpEnv &env, ByteStrBuff& flatStr)
215
  {
M
Michiharu Ariza 已提交
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
    if (unlikely (!SUPER::process_op (op, env, flatStr)))
      return false;
    switch (op)
    {
      case OpCode_hintmask:
      case OpCode_cntrmask:
        if (unlikely (!flatStr.encode_op (op)))
          return false;
        for (int i = -env.hintmask_size; i < 0; i++)
          if (unlikely (!flatStr.encode_byte (env.substr[i])))
            return false;
        break;
      default:
        if (!CSOpSet::is_subr_op (op) &&
            !CSOpSet::is_arg_op (op))
          return flatStr.encode_op (op);
    }
    return true;
234 235
  }

M
Michiharu Ariza 已提交
236
  static inline void flush_stack (CFF1CSInterpEnv &env, ByteStrBuff& flatStr)
237
  {
M
Michiharu Ariza 已提交
238 239 240
    for (unsigned int i = 0; i < env.argStack.size; i++)
      flatStr.encode_num (env.argStack.elements[i]);
    SUPER::flush_stack (env, flatStr);
241
  }
M
Michiharu Ariza 已提交
242 243 244

  private:
  typedef CFF1CSOpSet<CFF1CSOpSet_Flatten, ByteStrBuff> SUPER;
245 246
};

M
Michiharu Ariza 已提交
247
struct CFF1CSOpSet_SubsetSubrs : CFF1CSOpSet<CFF1CSOpSet_SubsetSubrs, SubrRefMapPair>
M
Michiharu Ariza 已提交
248
{
249
  static inline bool process_op (OpCode op, CFF1CSInterpEnv &env, SubrRefMapPair& refMapPair)
M
Michiharu Ariza 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
  {
    unsigned int  subr_num;
    switch (op) {
      case OpCode_callsubr:
        if (!unlikely (env.popSubrNum(env.localSubrs, subr_num)))
          return false;
        env.argStack.unpop ();
        refMapPair.local_map->add (subr_num);
        break;
      case OpCode_callgsubr:
        if (!unlikely (env.popSubrNum(env.globalSubrs, subr_num)))
          return false;
        env.argStack.unpop ();
        refMapPair.global_map->add (subr_num);
        break;
      default:
        break;
    }
M
Michiharu Ariza 已提交
268
    return CFF1CSOpSet<CFF1CSOpSet_SubsetSubrs, SubrRefMapPair>::process_op (op, env, refMapPair);
M
Michiharu Ariza 已提交
269 270 271
  }
};

M
Michiharu Ariza 已提交
272 273 274 275
struct cff_subset_plan {
  inline cff_subset_plan (void)
    : final_size (0),
      orig_fdcount (0),
M
Michiharu Ariza 已提交
276
      subst_fdcount (1),
M
Michiharu Ariza 已提交
277
      subst_fdselect_format (0),
M
Michiharu Ariza 已提交
278 279 280
      offsets (),
      flatten_subrs (true),
      drop_hints (false)
M
Michiharu Ariza 已提交
281 282 283 284 285 286
  {
    topdict_sizes.init ();
    topdict_sizes.resize (1);
    subst_fdselect_first_glyphs.init ();
    fdmap.init ();
    subset_charstrings.init ();
M
Michiharu Ariza 已提交
287
    flat_charstrings.init ();
M
Michiharu Ariza 已提交
288
    privateDictInfos.init ();
M
Michiharu Ariza 已提交
289
    subrRefMaps.init ();
M
Michiharu Ariza 已提交
290 291 292 293 294 295 296 297
  }

  inline ~cff_subset_plan (void)
  {
    topdict_sizes.fini ();
    subst_fdselect_first_glyphs.fini ();
    fdmap.fini ();
    subset_charstrings.fini ();
M
Michiharu Ariza 已提交
298
    flat_charstrings.fini ();
M
Michiharu Ariza 已提交
299
    privateDictInfos.fini ();
M
Michiharu Ariza 已提交
300
    subrRefMaps.fini ();
M
Michiharu Ariza 已提交
301 302
  }

303
  inline bool create (const OT::cff1::accelerator_subset_t &acc,
M
Michiharu Ariza 已提交
304 305 306 307
                      hb_subset_plan_t *plan)
  {
    final_size = 0;
    orig_fdcount = acc.fdCount;
308
    drop_hints = plan->drop_hints;
M
Michiharu Ariza 已提交
309 310

    /* CFF header */
311
    final_size += OT::cff1::static_size;
M
Michiharu Ariza 已提交
312 313 314 315 316 317 318
    
    /* Name INDEX */
    offsets.nameIndexOffset = final_size;
    final_size += acc.nameIndex->get_size ();
    
    /* top dict INDEX */
    {
M
Michiharu Ariza 已提交
319
      offsets.topDictInfo.offset = final_size;
320
      CFF1TopDict_OpSerializer topSzr;
M
Michiharu Ariza 已提交
321
      unsigned int topDictSize = TopDict::calculate_serialized_size (acc.topDicts[0], topSzr);
M
Michiharu Ariza 已提交
322
      offsets.topDictInfo.offSize = calcOffSize(topDictSize);
323
      final_size += CFF1IndexOf<TopDict>::calculate_serialized_size<CFF1TopDictValues> (offsets.topDictInfo.offSize, acc.topDicts, topdict_sizes, topSzr);
M
Michiharu Ariza 已提交
324 325 326 327 328 329
    }

    /* String INDEX */
    offsets.stringIndexOffset = final_size;
    final_size += acc.stringIndex->get_size ();
    
M
Michiharu Ariza 已提交
330 331 332 333 334 335 336 337 338 339 340
    if (flatten_subrs)
    {
      /* Flatten global & local subrs */
      SubrFlattener<const OT::cff1::accelerator_subset_t, CFF1CSInterpEnv, CFF1CSOpSet_Flatten> flattener(acc, plan->glyphs);
      if (!flattener.flatten (flat_charstrings))
        return false;
      
      /* no global/local subroutines */
      offsets.globalSubrsInfo.size = HBUINT16::static_size; /* count 0 only */
    }
    else
M
Michiharu Ariza 已提交
341
    {
M
Michiharu Ariza 已提交
342 343
      /* Subset global & local subrs */
      SubrSubsetter<const OT::cff1::accelerator_subset_t, CFF1CSInterpEnv, CFF1CSOpSet_SubsetSubrs> subsetter(acc, plan->glyphs);
M
Michiharu Ariza 已提交
344 345 346 347 348 349 350 351 352
      if (!subsetter.collect_refs (subrRefMaps))
        return false;
      
      offsets.globalSubrsInfo.size = acc.globalSubrs->calculate_serialized_size (offsets.globalSubrsInfo.offSize, subrRefMaps.global_map, 1);
      if (!offsets.localSubrsInfos.resize (orig_fdcount))
        return false;
      for (unsigned int i = 0; i < orig_fdcount; i++)
        offsets.localSubrsInfos[i].size = acc.privateDicts[i].localSubrs->calculate_serialized_size (offsets.localSubrsInfos[i].offSize, subrRefMaps.local_maps[i], 1);
    }
M
Michiharu Ariza 已提交
353
    /* global subrs */
M
Michiharu Ariza 已提交
354 355
    offsets.globalSubrsInfo.offset = final_size;
    final_size += offsets.globalSubrsInfo.size;
M
Michiharu Ariza 已提交
356 357 358 359 360 361 362 363 364 365 366 367

    /* Encoding */
    offsets.encodingOffset = final_size;
    if (acc.encoding != &Null(Encoding))
      final_size += acc.encoding->get_size ();

    /* Charset */
    offsets.charsetOffset = final_size;
    if (acc.charset != &Null(Charset))
      final_size += acc.charset->get_size (acc.num_glyphs);

    /* FDSelect */
368
    if (acc.fdSelect != &Null(CFF1FDSelect))
M
Michiharu Ariza 已提交
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
    {
      offsets.FDSelectInfo.offset = final_size;
      if (unlikely (!hb_plan_subset_cff_fdselect (plan->glyphs,
                                  orig_fdcount,
                                  *acc.fdSelect,
                                  subst_fdcount,
                                  offsets.FDSelectInfo.size,
                                  subst_fdselect_format,
                                  subst_fdselect_first_glyphs,
                                  fdmap)))
        return false;
      
      if (!is_fds_subsetted ())
        offsets.FDSelectInfo.size = acc.fdSelect->calculate_serialized_size (acc.num_glyphs);
      final_size += offsets.FDSelectInfo.size;
    }

    /* FDArray (FDIndex) */
387
    if (acc.fdArray != &Null(CFF1FDArray)) {
M
Michiharu Ariza 已提交
388
      offsets.FDArrayInfo.offset = final_size;
389 390
      CFF1FontDict_OpSerializer fontSzr;
      final_size += CFF1FDArray::calculate_serialized_size(offsets.FDArrayInfo.offSize/*OUT*/, acc.fontDicts, subst_fdcount, fdmap, fontSzr);
M
Michiharu Ariza 已提交
391 392 393 394
    }

    /* CharStrings */
    {
M
Michiharu Ariza 已提交
395
      offsets.charStringsInfo.offset = final_size;
M
Michiharu Ariza 已提交
396 397 398
      unsigned int dataSize = 0;
      for (unsigned int i = 0; i < plan->glyphs.len; i++)
      {
M
Michiharu Ariza 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411
        if (flatten_subrs)
        {
          ByteStrBuff &flatstr = flat_charstrings[i];
          ByteStr str (&flatstr[0], flatstr.len);
          subset_charstrings.push (str);
          dataSize += flatstr.len;
        }
        else
        {
          const ByteStr str = (*acc.charStrings)[plan->glyphs[i]];
          subset_charstrings.push (str);
          dataSize += str.len;
        }
M
Michiharu Ariza 已提交
412
      }
M
Michiharu Ariza 已提交
413
      offsets.charStringsInfo.offSize = calcOffSize (dataSize + 1);
414
      final_size += CFF1CharStrings::calculate_serialized_size (offsets.charStringsInfo.offSize, plan->glyphs.len, dataSize);
M
Michiharu Ariza 已提交
415 416 417 418 419 420
    }

    /* private dicts & local subrs */
    offsets.privateDictInfo.offset = final_size;
    for (unsigned int i = 0; i < orig_fdcount; i++)
    {
421 422
      if (!fdmap.excludes (i))
      {
423
        unsigned int  priv_size;
M
Michiharu Ariza 已提交
424 425
        CFF1PrivateDict_OpSerializer privSzr (plan->drop_hints, flatten_subrs);
        priv_size = PrivateDict::calculate_serialized_size (acc.privateDicts[i], privSzr);
426
        TableInfo  privInfo = { final_size, priv_size, 0 };
427
        privateDictInfos.push (privInfo);
M
Michiharu Ariza 已提交
428 429 430
        final_size += privInfo.size;
        if (!flatten_subrs)
          final_size += offsets.localSubrsInfos[i].size;
431
      }
M
Michiharu Ariza 已提交
432 433 434 435 436
    }

    if (!acc.is_CID ())
      offsets.privateDictInfo = privateDictInfos[0];

M
Michiharu Ariza 已提交
437 438
    return ((subset_charstrings.len == plan->glyphs.len) &&
            (privateDictInfos.len == subst_fdcount));
M
Michiharu Ariza 已提交
439 440 441 442 443 444
  }

  inline unsigned int get_final_size (void) const  { return final_size; }

  unsigned int        final_size;
  hb_vector_t<unsigned int> topdict_sizes;
445
  CFF1SubTableOffsets  offsets;
M
Michiharu Ariza 已提交
446 447 448 449 450 451 452 453 454

  unsigned int    orig_fdcount;
  unsigned int    subst_fdcount;
  inline bool     is_fds_subsetted (void) const { return subst_fdcount < orig_fdcount; }
  unsigned int    subst_fdselect_format;
  hb_vector_t<hb_codepoint_t>   subst_fdselect_first_glyphs;

  /* font dict index remap table from fullset FDArray to subset FDArray.
   * set to HB_SET_VALUE_INVALID if excluded from subset */
455
  FDMap   fdmap;
M
Michiharu Ariza 已提交
456

M
Michiharu Ariza 已提交
457 458 459
  hb_vector_t<ByteStr>    subset_charstrings;
  ByteStrBuffArray        flat_charstrings;
  hb_vector_t<TableInfo>  privateDictInfos;
M
Michiharu Ariza 已提交
460 461

  SubrRefMaps             subrRefMaps;
462

M
Michiharu Ariza 已提交
463
  bool            flatten_subrs;
464
  bool            drop_hints;
M
Michiharu Ariza 已提交
465 466
};

467
static inline bool _write_cff1 (const cff_subset_plan &plan,
468
                                const OT::cff1::accelerator_subset_t  &acc,
M
Michiharu Ariza 已提交
469 470 471 472 473 474
                                const hb_vector_t<hb_codepoint_t>& glyphs,
                                unsigned int dest_sz,
                                void *dest)
{
  hb_serialize_context_t c (dest, dest_sz);

M
Michiharu Ariza 已提交
475
  char RETURN_OP[1] = { OpCode_return };
M
Michiharu Ariza 已提交
476
  const ByteStr NULL_SUBR (RETURN_OP, 1);
M
Michiharu Ariza 已提交
477

478
  OT::cff1 *cff = c.start_serialize<OT::cff1> ();
M
Michiharu Ariza 已提交
479 480 481 482 483 484 485 486 487 488 489 490
  if (unlikely (!c.extend_min (*cff)))
    return false;

  /* header */
  cff->version.major.set (0x01);
  cff->version.minor.set (0x00);
  cff->nameIndex.set (cff->min_size);
  cff->offSize.set (4); /* unused? */

  /* name INDEX */
  {
    assert (cff->nameIndex == c.head - c.start);
491
    CFF1NameIndex *dest = c.start_embed<CFF1NameIndex> ();
M
Michiharu Ariza 已提交
492 493 494 495 496 497 498 499 500 501
    if (unlikely (dest == nullptr)) return false;
    if (unlikely (!dest->serialize (&c, *acc.nameIndex)))
    {
      DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF name INDEX");
      return false;
    }
  }

  /* top dict INDEX */
  {
M
Michiharu Ariza 已提交
502
    assert (plan.offsets.topDictInfo.offset == c.head - c.start);
503
    CFF1IndexOf<TopDict> *dest = c.start_embed< CFF1IndexOf<TopDict> > ();
M
Michiharu Ariza 已提交
504
    if (dest == nullptr) return false;
505
    CFF1TopDict_OpSerializer topSzr;
M
Michiharu Ariza 已提交
506
    if (unlikely (!dest->serialize (&c, plan.offsets.topDictInfo.offSize, acc.topDicts, plan.topdict_sizes, topSzr, plan.offsets)))
M
Michiharu Ariza 已提交
507 508 509 510 511 512 513 514 515
    {
      DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF top dict");
      return false;
    }
  }

  /* String INDEX */
  {
    assert (plan.offsets.stringIndexOffset == c.head - c.start);
516
    CFF1StringIndex *dest = c.start_embed<CFF1StringIndex> ();
M
Michiharu Ariza 已提交
517 518 519 520 521 522 523 524 525 526
    if (unlikely (dest == nullptr)) return false;
    if (unlikely (!dest->serialize (&c, *acc.stringIndex)))
    {
      DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF string INDEX");
      return false;
    }
  }

  /* global subrs */
  {
M
Michiharu Ariza 已提交
527
    assert (plan.offsets.globalSubrsInfo.offset != 0);
M
Michiharu Ariza 已提交
528
    assert (plan.offsets.globalSubrsInfo.offset == c.head - c.start);
529
    CFF1Subrs *dest = c.start_embed<CFF1Subrs> ();
M
Michiharu Ariza 已提交
530
    if (unlikely (dest == nullptr)) return false;
M
Michiharu Ariza 已提交
531
    if (unlikely (!dest->serialize (&c, *acc.globalSubrs, plan.offsets.globalSubrsInfo.offSize, plan.subrRefMaps.global_map, NULL_SUBR)))
M
Michiharu Ariza 已提交
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
    {
      DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF global subrs");
      return false;
    }
  }

  /* Encoding */
  if (acc.encoding != &Null(Encoding)){
    assert (plan.offsets.encodingOffset == c.head - c.start);
    Encoding *dest = c.start_embed<Encoding> ();
    if (unlikely (dest == nullptr)) return false;
    if (unlikely (!dest->serialize (&c, *acc.encoding, acc.num_glyphs)))  // XXX: TODO
    {
      DEBUG_MSG (SUBSET, nullptr, "failed to serialize Encoding");
      return false;
    }
  }

  /* Charset */
  if (acc.charset != &Null(Charset))
  {
    assert (plan.offsets.charsetOffset == c.head - c.start);
    Charset *dest = c.start_embed<Charset> ();
    if (unlikely (dest == nullptr)) return false;
    if (unlikely (!dest->serialize (&c, *acc.charset, acc.num_glyphs)))  // XXX: TODO
    {
      DEBUG_MSG (SUBSET, nullptr, "failed to serialize Charset");
      return false;
    }
  }

  /* FDSelect */
564
  if (acc.fdSelect != &Null(CFF1FDSelect))
M
Michiharu Ariza 已提交
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
  {
    assert (plan.offsets.FDSelectInfo.offset == c.head - c.start);
    
    if (plan.is_fds_subsetted ())
    {
      if (unlikely (!hb_serialize_cff_fdselect (&c, glyphs, *acc.fdSelect, acc.fdCount,
                                                plan.subst_fdselect_format, plan.offsets.FDSelectInfo.size,
                                                plan.subst_fdselect_first_glyphs,
                                                plan.fdmap)))
      {
        DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF subset FDSelect");
        return false;
      }
    }
    else
    {
581
      CFF1FDSelect *dest = c.start_embed<CFF1FDSelect> ();
M
Michiharu Ariza 已提交
582 583 584 585 586 587 588 589 590
      if (unlikely (!dest->serialize (&c, *acc.fdSelect, acc.num_glyphs)))
      {
        DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF FDSelect");
        return false;
      }
    }
  }

  /* FDArray (FD Index) */
591
  if (acc.fdArray != &Null(CFF1FDArray))
M
Michiharu Ariza 已提交
592
  {
M
Michiharu Ariza 已提交
593
    assert (plan.offsets.FDArrayInfo.offset == c.head - c.start);
594
    CFF1FDArray  *fda = c.start_embed<CFF1FDArray> ();
M
Michiharu Ariza 已提交
595
    if (unlikely (fda == nullptr)) return false;
596
    CFF1FontDict_OpSerializer  fontSzr;
M
Michiharu Ariza 已提交
597
    if (unlikely (!fda->serialize (&c, plan.offsets.FDArrayInfo.offSize,
M
Michiharu Ariza 已提交
598 599 600 601 602 603 604 605 606 607
                                   acc.fontDicts, plan.subst_fdcount, plan.fdmap,
                                   fontSzr, plan.privateDictInfos)))
    {
      DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF FDArray");
      return false;
    }
  }

  /* CharStrings */
  {
M
Michiharu Ariza 已提交
608
    assert (plan.offsets.charStringsInfo.offset == c.head - c.start);
609
    CFF1CharStrings  *cs = c.start_embed<CFF1CharStrings> ();
M
Michiharu Ariza 已提交
610
    if (unlikely (cs == nullptr)) return false;
M
Michiharu Ariza 已提交
611
    if (unlikely (!cs->serialize (&c, plan.offsets.charStringsInfo.offSize, plan.subset_charstrings)))
M
Michiharu Ariza 已提交
612 613 614 615 616 617 618 619 620 621
    {
      DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF CharStrings");
      return false;
    }
  }

  /* private dicts & local subrs */
  assert (plan.offsets.privateDictInfo.offset == c.head - c.start);
  for (unsigned int i = 0; i < acc.privateDicts.len; i++)
  {
622
    if (!plan.fdmap.excludes (i))
M
Michiharu Ariza 已提交
623
    {
624 625
      PrivateDict  *pd = c.start_embed<PrivateDict> ();
      if (unlikely (pd == nullptr)) return false;
M
Michiharu Ariza 已提交
626
      unsigned int priv_size = plan.flatten_subrs? 0: plan.privateDictInfos[plan.fdmap[i]].size;
627
      bool result;
M
Michiharu Ariza 已提交
628
      CFF1PrivateDict_OpSerializer privSzr (plan.drop_hints, plan.flatten_subrs);
629
      /* N.B. local subrs immediately follows its corresponding private dict. i.e., subr offset == private dict size */
M
Michiharu Ariza 已提交
630
      result = pd->serialize (&c, acc.privateDicts[i], privSzr, priv_size);
631
      if (unlikely (!result))
M
Michiharu Ariza 已提交
632
      {
633
        DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF Private Dict[%d]", i);
M
Michiharu Ariza 已提交
634 635
        return false;
      }
M
Michiharu Ariza 已提交
636
      if (!plan.flatten_subrs && (acc.privateDicts[i].subrsOffset != 0))
M
Michiharu Ariza 已提交
637
      {
638 639
        CFF1Subrs *subrs = c.start_embed<CFF1Subrs> ();
        if (unlikely (subrs == nullptr) || acc.privateDicts[i].localSubrs == &Null(CFF1Subrs))
640 641 642 643
        {
          DEBUG_MSG (SUBSET, nullptr, "CFF subset: local subrs unexpectedly null [%d]", i);
          return false;
        }
M
Michiharu Ariza 已提交
644
        if (unlikely (!subrs->serialize (&c, *acc.privateDicts[i].localSubrs, plan.offsets.localSubrsInfos[i].offSize, plan.subrRefMaps.local_maps[i], NULL_SUBR)))
645 646 647 648
        {
          DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF local subrs [%d]", i);
          return false;
        }
M
Michiharu Ariza 已提交
649 650 651 652
      }
    }
  }

M
Michiharu Ariza 已提交
653
  assert (c.head == c.end);
M
Michiharu Ariza 已提交
654 655 656 657 658 659
  c.end_serialize ();

  return true;
}

static bool
660
_hb_subset_cff1 (const OT::cff1::accelerator_subset_t  &acc,
M
Michiharu Ariza 已提交
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
                const char                      *data,
                hb_subset_plan_t                *plan,
                hb_blob_t                       **prime /* OUT */)
{
  cff_subset_plan cff_plan;

  if (unlikely (!cff_plan.create (acc, plan)))
  {
    DEBUG_MSG(SUBSET, nullptr, "Failed to generate a cff subsetting plan.");
    return false;
  }

  unsigned int  cff_prime_size = cff_plan.get_final_size ();
  char *cff_prime_data = (char *) calloc (1, cff_prime_size);

676
  if (unlikely (!_write_cff1 (cff_plan, acc, plan->glyphs,
M
Michiharu Ariza 已提交
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
                              cff_prime_size, cff_prime_data))) {
    DEBUG_MSG(SUBSET, nullptr, "Failed to write a subset cff.");
    free (cff_prime_data);
    return false;
  }

  *prime = hb_blob_create (cff_prime_data,
                           cff_prime_size,
                           HB_MEMORY_MODE_READONLY,
                           cff_prime_data,
                           free);
  return true;
}

/**
692
 * hb_subset_cff1:
M
Michiharu Ariza 已提交
693 694 695 696 697
 * Subsets the CFF table according to a provided plan.
 *
 * Return value: subsetted cff table.
 **/
bool
698
hb_subset_cff1 (hb_subset_plan_t *plan,
M
Michiharu Ariza 已提交
699 700
                hb_blob_t       **prime /* OUT */)
{
701
  hb_blob_t *cff_blob = hb_sanitize_context_t().reference_table<CFF::cff1> (plan->source);
M
Michiharu Ariza 已提交
702 703
  const char *data = hb_blob_get_data(cff_blob, nullptr);

704
  OT::cff1::accelerator_subset_t acc;
M
Michiharu Ariza 已提交
705 706
  acc.init(plan->source);
  bool result = likely (acc.is_valid ()) &&
707
                        _hb_subset_cff1 (acc, data, plan, prime);
M
Michiharu Ariza 已提交
708 709 710 711 712
  hb_blob_destroy (cff_blob);
  acc.fini ();

  return result;
}