hb-subset-cff1.cc 26.5 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
/*
 * 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
 */

27
#include "hb-open-type.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
#include "hb-subset-plan.hh"
32
#include "hb-subset-cff-common.hh"
33
#include "hb-cff1-interp-cs.hh"
M
Michiharu Ariza 已提交
34 35 36

using namespace CFF;

M
Michiharu Ariza 已提交
37 38
struct CFF1SubTableOffsets : CFFSubTableOffsets
{
39
  inline CFF1SubTableOffsets (void)
M
Michiharu Ariza 已提交
40 41 42 43 44
    : CFFSubTableOffsets (),
      nameIndexOffset (0),
      stringIndexOffset (0),
      encodingOffset (0),
      charsetOffset (0)
M
Michiharu Ariza 已提交
45
  {
M
Michiharu Ariza 已提交
46
    privateDictInfo.init ();
M
Michiharu Ariza 已提交
47 48 49 50 51 52 53 54 55
  }

  unsigned int  nameIndexOffset;
  unsigned int  stringIndexOffset;
  unsigned int  encodingOffset;
  unsigned int  charsetOffset;
  TableInfo     privateDictInfo;
};

M
Michiharu Ariza 已提交
56
struct CFF1TopDict_OpSerializer : CFFTopDict_OpSerializer
M
Michiharu Ariza 已提交
57 58 59
{
  inline bool serialize (hb_serialize_context_t *c,
                         const OpStr &opstr,
60
                         const CFF1SubTableOffsets &offsets) const
M
Michiharu Ariza 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
  {
    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_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:
M
Michiharu Ariza 已提交
85
        return_trace (CFFTopDict_OpSerializer::serialize (c, opstr, offsets));
M
Michiharu Ariza 已提交
86 87 88 89 90 91 92 93 94 95
    }
    return_trace (true);
  }

  inline unsigned int calculate_serialized_size (const OpStr &opstr) const
  {
    switch (opstr.op)
    {
      case OpCode_charset:
      case OpCode_Encoding:
M
Michiharu Ariza 已提交
96
        return OpCode_Size (OpCode_longintdict) + 4 + OpCode_Size (opstr.op);
M
Michiharu Ariza 已提交
97 98
    
      case OpCode_Private:
M
Michiharu Ariza 已提交
99
        return OpCode_Size (OpCode_longintdict) + 4 + OpCode_Size (OpCode_shortint) + 2 + OpCode_Size (OpCode_Private);
M
Michiharu Ariza 已提交
100 101
    
      default:
M
Michiharu Ariza 已提交
102
        return CFFTopDict_OpSerializer::calculate_serialized_size (opstr);
M
Michiharu Ariza 已提交
103 104 105 106
    }
  }
};

107
struct CFF1CSOpSet_Flatten : CFF1CSOpSet<CFF1CSOpSet_Flatten, FlattenParam>
108
{
109
  static inline void flush_args_and_op (OpCode op, CFF1CSInterpEnv &env, FlattenParam& param)
110
  {
M
Michiharu Ariza 已提交
111 112
    switch (op)
    {
113 114 115 116
      case OpCode_hstem:
      case OpCode_hstemhm:
      case OpCode_vstem:
      case OpCode_vstemhm:
M
Michiharu Ariza 已提交
117 118
      case OpCode_hintmask:
      case OpCode_cntrmask:
119 120 121 122
      case OpCode_hflex:
      case OpCode_flex:
      case OpCode_hflex1:
      case OpCode_flex1:
123 124
        if (param.drop_hints)
        {
125 126
          env.clear_args ();
          return;
127
        }
128 129
        /* NO BREAK */

M
Michiharu Ariza 已提交
130
      default:
131 132
        SUPER::flush_args_and_op (op, env, param);
        break;
M
Michiharu Ariza 已提交
133
    }
134 135
  }

136
  static inline void flush_n_args (unsigned int n, CFF1CSInterpEnv &env, FlattenParam& param)
137
  {
138
    for (unsigned int i = env.argStack.count - n; i < env.argStack.count; i++)
139
      param.flatStr.encode_num (env.argStack.elements[i]);
140 141 142 143 144 145 146 147 148 149 150
    SUPER::flush_n_args (n, env, param);
  }

  static inline void flush_op (OpCode op, CFF1CSInterpEnv &env, FlattenParam& param)
  {
    param.flatStr.encode_op (op);
  }

  static inline void flush_hintmask (OpCode op, CFF1CSInterpEnv &env, FlattenParam& param)
  {
    SUPER::flush_hintmask (op, env, param);
151 152 153
    if (!param.drop_hints)
      for (unsigned int i = 0; i < env.hintmask_size; i++)
        param.flatStr.encode_byte (env.substr[i]);
154
  }
M
Michiharu Ariza 已提交
155 156

  private:
157
  typedef CFF1CSOpSet<CFF1CSOpSet_Flatten, FlattenParam> SUPER;
158 159
};

M
Michiharu Ariza 已提交
160
struct CFF1CSOpSet_SubsetSubrs : CFF1CSOpSet<CFF1CSOpSet_SubsetSubrs, SubrRefMapPair>
M
Michiharu Ariza 已提交
161
{
162
  static inline bool process_op (OpCode op, CFF1CSInterpEnv &env, SubrRefMapPair& refMapPair)
M
Michiharu Ariza 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
  {
    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 已提交
181
    return CFF1CSOpSet<CFF1CSOpSet_SubsetSubrs, SubrRefMapPair>::process_op (op, env, refMapPair);
M
Michiharu Ariza 已提交
182 183 184
  }
};

M
Michiharu Ariza 已提交
185 186 187 188
struct cff_subset_plan {
  inline cff_subset_plan (void)
    : final_size (0),
      orig_fdcount (0),
M
Michiharu Ariza 已提交
189 190
      subset_fdcount (1),
      subset_fdselect_format (0),
M
Michiharu Ariza 已提交
191 192 193
      offsets (),
      flatten_subrs (true),
      drop_hints (false)
M
Michiharu Ariza 已提交
194 195 196
  {
    topdict_sizes.init ();
    topdict_sizes.resize (1);
M
Michiharu Ariza 已提交
197 198
    topdict_mod.init ();
    subset_fdselect_first_glyphs.init ();
M
Michiharu Ariza 已提交
199 200
    fdmap.init ();
    subset_charstrings.init ();
M
Michiharu Ariza 已提交
201
    flat_charstrings.init ();
M
Michiharu Ariza 已提交
202
    privateDictInfos.init ();
M
Michiharu Ariza 已提交
203
    subrRefMaps.init ();
M
Michiharu Ariza 已提交
204 205 206
    subset_enc_code_ranges.init ();
    subset_enc_supp_codes.init ();
    subset_charset_ranges.init ();
M
Michiharu Ariza 已提交
207 208 209 210 211
  }

  inline ~cff_subset_plan (void)
  {
    topdict_sizes.fini ();
M
Michiharu Ariza 已提交
212 213
    topdict_mod.fini ();
    subset_fdselect_first_glyphs.fini ();
M
Michiharu Ariza 已提交
214 215
    fdmap.fini ();
    subset_charstrings.fini ();
M
Michiharu Ariza 已提交
216
    flat_charstrings.fini ();
M
Michiharu Ariza 已提交
217
    privateDictInfos.fini ();
M
Michiharu Ariza 已提交
218
    subrRefMaps.fini ();
M
Michiharu Ariza 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    subset_enc_code_ranges.fini ();
    subset_enc_supp_codes.init ();
    subset_charset_ranges.fini ();
  }

  inline unsigned int plan_subset_encoding (const OT::cff1::accelerator_subset_t &acc, hb_subset_plan_t *plan)
  {
    const Encoding *encoding = acc.encoding;
    unsigned int  size0, size1, supp_size;
    hb_codepoint_t  code, last_code = CFF_UNDEF_CODE;
    hb_vector_t<hb_codepoint_t> supp_codes;

    subset_enc_code_ranges.resize (0);
    supp_size = 0;
    supp_codes.init ();

    subset_enc_num_codes = plan->glyphs.len - 1;
    unsigned int glyph;
    for (glyph = 1; glyph < plan->glyphs.len; glyph++)
    {
      hb_codepoint_t  orig_glyph = plan->glyphs[glyph];
      code = acc.glyph_to_code (orig_glyph);
      if (code == CFF_UNDEF_CODE)
      {
        subset_enc_num_codes = glyph - 1;
        break;
      }

      if (code != last_code + 1)
      {
        if (subset_enc_code_ranges.len > 0)
        {
          code_pair &pair = subset_enc_code_ranges[subset_enc_code_ranges.len - 1];
          pair.glyph = glyph - pair.glyph - 1;
        }
        code_pair pair = { code, glyph };
        subset_enc_code_ranges.push (pair);
      }
      last_code = code;

      if (encoding != &Null(Encoding))
      {
        hb_codepoint_t  sid = acc.glyph_to_sid (orig_glyph);
        encoding->get_supplement_codes (sid, supp_codes);
        for (unsigned int i = 0; i < supp_codes.len; i++)
        {
          code_pair pair = { supp_codes[i], sid };
          subset_enc_supp_codes.push (pair);
        }
        supp_size += SuppEncoding::static_size * supp_codes.len;
      }
    }
    supp_codes.fini ();
    if (subset_enc_code_ranges.len > 0)
    {
      code_pair &pair = subset_enc_code_ranges[subset_enc_code_ranges.len - 1];
      pair.glyph = glyph - pair.glyph - 1;
    }

    assert (subset_enc_num_codes <= 0xFF);
    size0 = Encoding0::min_size + HBUINT8::static_size * subset_enc_num_codes;
    size1 = Encoding1::min_size + Encoding1_Range::static_size * subset_enc_code_ranges.len;

    if (size0 < size1)
      subset_enc_format = 0;
    else
      subset_enc_format = 1;

    return Encoding::calculate_serialized_size (
                        subset_enc_format,
                        subset_enc_format? subset_enc_code_ranges.len: subset_enc_num_codes,
                        subset_enc_supp_codes.len);
  }

  inline unsigned int plan_subset_charset (const OT::cff1::accelerator_subset_t &acc, hb_subset_plan_t *plan)
  {
    unsigned int  size0, size_ranges;
    hb_codepoint_t  sid, last_sid = CFF_UNDEF_CODE;
    bool  two_byte = false;

    subset_charset_ranges.resize (0);
    unsigned int glyph;
    for (glyph = 1; glyph < plan->glyphs.len; glyph++)
    {
      hb_codepoint_t  orig_glyph = plan->glyphs[glyph];
      sid = acc.glyph_to_sid (orig_glyph);

      if (sid != last_sid + 1)
      {
        if (subset_charset_ranges.len > 0)
        {
          code_pair &pair = subset_charset_ranges[subset_charset_ranges.len - 1];
          pair.glyph = glyph - pair.glyph - 1;
          if ((pair.glyph & ~0xFF) != 0) two_byte = true;
        }
        code_pair pair = { sid, glyph };
        subset_charset_ranges.push (pair);
      }
      last_sid = sid;
    }

    if (subset_charset_ranges.len > 0)
    {
      code_pair &pair = subset_charset_ranges[subset_charset_ranges.len - 1];
      pair.glyph = glyph - pair.glyph - 1;
      if ((pair.glyph & ~0xFF) != 0) two_byte = true;
    }

    size0 = Charset0::min_size + HBUINT16::static_size * (plan->glyphs.len - 1);
    if (!two_byte)
      size_ranges = Charset1::min_size + Charset1_Range::static_size * subset_charset_ranges.len;
    else
      size_ranges = Charset2::min_size + Charset2_Range::static_size * subset_charset_ranges.len;

    if (size0 < size_ranges)
      subset_charset_format = 0;
    else if (!two_byte)
      subset_charset_format = 1;
    else
      subset_charset_format = 2;

    return Charset::calculate_serialized_size (
                        subset_charset_format,
                        subset_charset_format? subset_charset_ranges.len: plan->glyphs.len);
M
Michiharu Ariza 已提交
343 344
  }

345
  inline bool create (const OT::cff1::accelerator_subset_t &acc,
M
Michiharu Ariza 已提交
346 347
                      hb_subset_plan_t *plan)
  {
M
Michiharu Ariza 已提交
348 349 350
     /* make sure notdef is first */
    if ((plan->glyphs.len == 0) || (plan->glyphs[0] != 0)) return false;

M
Michiharu Ariza 已提交
351
    final_size = 0;
M
Michiharu Ariza 已提交
352
    num_glyphs = plan->glyphs.len;
M
Michiharu Ariza 已提交
353
    orig_fdcount = acc.fdCount;
354
    drop_hints = plan->drop_hints;
M
Michiharu Ariza 已提交
355

M
Michiharu Ariza 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368
    /* check whether the subset renumbers any glyph IDs */
    gid_renum = false;
    for (unsigned int glyph = 0; glyph < plan->glyphs.len; glyph++)
    {
      if (plan->glyphs[glyph] != glyph) {
        gid_renum = true;
        break;
      }
    }

    subset_charset = gid_renum || !acc.is_predef_charset ();
    subset_encoding = !acc.is_CID() && (gid_renum || !acc.is_predef_encoding ());

M
Michiharu Ariza 已提交
369
    /* CFF header */
370
    final_size += OT::cff1::static_size;
M
Michiharu Ariza 已提交
371 372 373 374
    
    /* Name INDEX */
    offsets.nameIndexOffset = final_size;
    final_size += acc.nameIndex->get_size ();
M
Michiharu Ariza 已提交
375

M
Michiharu Ariza 已提交
376 377
    /* top dict INDEX */
    {
M
Michiharu Ariza 已提交
378 379 380 381 382 383 384 385 386 387 388
      /* Add encoding/charset to a (copy of) top dict as necessary */
      topdict_mod.init (&acc.topDicts[0]);
      bool need_to_add_enc = (subset_encoding && !acc.topDicts[0].hasOp (OpCode_Encoding));
      bool need_to_add_set = (subset_charset && !acc.topDicts[0].hasOp (OpCode_charset));
      if (need_to_add_enc || need_to_add_set)
      {
        if (need_to_add_enc)
          topdict_mod.addOp (OpCode_Encoding);
        if (need_to_add_set)
          topdict_mod.addOp (OpCode_charset);
      }
M
Michiharu Ariza 已提交
389
      offsets.topDictInfo.offset = final_size;
390
      CFF1TopDict_OpSerializer topSzr;
M
Michiharu Ariza 已提交
391
      unsigned int topDictSize = TopDict::calculate_serialized_size (topdict_mod, topSzr);
M
Michiharu Ariza 已提交
392
      offsets.topDictInfo.offSize = calcOffSize(topDictSize);
M
Michiharu Ariza 已提交
393 394 395
      final_size += CFF1IndexOf<TopDict>::calculate_serialized_size<CFF1TopDictValuesMod>
                                                (offsets.topDictInfo.offSize,
                                                 &topdict_mod, 1, topdict_sizes, topSzr);
M
Michiharu Ariza 已提交
396 397 398 399 400 401
    }

    /* String INDEX */
    offsets.stringIndexOffset = final_size;
    final_size += acc.stringIndex->get_size ();
    
M
Michiharu Ariza 已提交
402 403 404
    if (flatten_subrs)
    {
      /* Flatten global & local subrs */
405 406
      SubrFlattener<const OT::cff1::accelerator_subset_t, CFF1CSInterpEnv, CFF1CSOpSet_Flatten>
                    flattener(acc, plan->glyphs, plan->drop_hints);
M
Michiharu Ariza 已提交
407 408 409 410 411 412 413
      if (!flattener.flatten (flat_charstrings))
        return false;
      
      /* no global/local subroutines */
      offsets.globalSubrsInfo.size = HBUINT16::static_size; /* count 0 only */
    }
    else
M
Michiharu Ariza 已提交
414
    {
M
Michiharu Ariza 已提交
415 416
      /* Subset global & local subrs */
      SubrSubsetter<const OT::cff1::accelerator_subset_t, CFF1CSInterpEnv, CFF1CSOpSet_SubsetSubrs> subsetter(acc, plan->glyphs);
M
Michiharu Ariza 已提交
417 418 419 420 421 422 423 424 425
      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 已提交
426
    /* global subrs */
M
Michiharu Ariza 已提交
427 428
    offsets.globalSubrsInfo.offset = final_size;
    final_size += offsets.globalSubrsInfo.size;
M
Michiharu Ariza 已提交
429 430 431

    /* Encoding */
    offsets.encodingOffset = final_size;
M
Michiharu Ariza 已提交
432 433
    if (subset_encoding)
      final_size += plan_subset_encoding (acc, plan);
M
Michiharu Ariza 已提交
434 435 436

    /* Charset */
    offsets.charsetOffset = final_size;
M
Michiharu Ariza 已提交
437 438
    if (subset_charset)
      final_size += plan_subset_charset (acc, plan);
M
Michiharu Ariza 已提交
439 440

    /* FDSelect */
441
    if (acc.fdSelect != &Null(CFF1FDSelect))
M
Michiharu Ariza 已提交
442 443 444 445 446
    {
      offsets.FDSelectInfo.offset = final_size;
      if (unlikely (!hb_plan_subset_cff_fdselect (plan->glyphs,
                                  orig_fdcount,
                                  *acc.fdSelect,
M
Michiharu Ariza 已提交
447
                                  subset_fdcount,
M
Michiharu Ariza 已提交
448
                                  offsets.FDSelectInfo.size,
M
Michiharu Ariza 已提交
449 450
                                  subset_fdselect_format,
                                  subset_fdselect_first_glyphs,
M
Michiharu Ariza 已提交
451 452 453 454 455 456 457 458 459
                                  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) */
460
    if (acc.fdArray != &Null(CFF1FDArray)) {
M
Michiharu Ariza 已提交
461
      offsets.FDArrayInfo.offset = final_size;
M
Michiharu Ariza 已提交
462
      CFFFontDict_OpSerializer fontSzr;
M
Michiharu Ariza 已提交
463
      final_size += CFF1FDArray::calculate_serialized_size(offsets.FDArrayInfo.offSize/*OUT*/, acc.fontDicts, subset_fdcount, fdmap, fontSzr);
M
Michiharu Ariza 已提交
464 465 466 467
    }

    /* CharStrings */
    {
M
Michiharu Ariza 已提交
468
      offsets.charStringsInfo.offset = final_size;
M
Michiharu Ariza 已提交
469 470 471
      unsigned int dataSize = 0;
      for (unsigned int i = 0; i < plan->glyphs.len; i++)
      {
M
Michiharu Ariza 已提交
472 473 474 475 476 477 478 479 480 481 482 483 484
        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 已提交
485
      }
M
Michiharu Ariza 已提交
486
      offsets.charStringsInfo.offSize = calcOffSize (dataSize + 1);
487
      final_size += CFF1CharStrings::calculate_serialized_size (offsets.charStringsInfo.offSize, plan->glyphs.len, dataSize);
M
Michiharu Ariza 已提交
488 489 490 491 492 493
    }

    /* private dicts & local subrs */
    offsets.privateDictInfo.offset = final_size;
    for (unsigned int i = 0; i < orig_fdcount; i++)
    {
494 495
      if (!fdmap.excludes (i))
      {
496
        unsigned int  priv_size;
M
Michiharu Ariza 已提交
497
        CFFPrivateDict_OpSerializer privSzr (plan->drop_hints, flatten_subrs);
M
Michiharu Ariza 已提交
498
        priv_size = PrivateDict::calculate_serialized_size (acc.privateDicts[i], privSzr);
499
        TableInfo  privInfo = { final_size, priv_size, 0 };
500
        privateDictInfos.push (privInfo);
M
Michiharu Ariza 已提交
501 502 503
        final_size += privInfo.size;
        if (!flatten_subrs)
          final_size += offsets.localSubrsInfos[i].size;
504
      }
M
Michiharu Ariza 已提交
505 506 507 508 509
    }

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

M
Michiharu Ariza 已提交
510
    return ((subset_charstrings.len == plan->glyphs.len) &&
M
Michiharu Ariza 已提交
511
            (privateDictInfos.len == subset_fdcount));
M
Michiharu Ariza 已提交
512 513 514 515
  }

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

M
Michiharu Ariza 已提交
516
  unsigned int              final_size;
M
Michiharu Ariza 已提交
517
  hb_vector_t<unsigned int> topdict_sizes;
M
Michiharu Ariza 已提交
518 519
  CFF1TopDictValuesMod      topdict_mod;
  CFF1SubTableOffsets       offsets;
M
Michiharu Ariza 已提交
520

M
Michiharu Ariza 已提交
521
  unsigned int    num_glyphs;
M
Michiharu Ariza 已提交
522
  unsigned int    orig_fdcount;
M
Michiharu Ariza 已提交
523 524 525 526
  unsigned int    subset_fdcount;
  inline bool     is_fds_subsetted (void) const { return subset_fdcount < orig_fdcount; }
  unsigned int    subset_fdselect_format;
  hb_vector_t<hb_codepoint_t>   subset_fdselect_first_glyphs;
M
Michiharu Ariza 已提交
527 528 529

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

M
Michiharu Ariza 已提交
532 533 534
  hb_vector_t<ByteStr>    subset_charstrings;
  ByteStrBuffArray        flat_charstrings;
  hb_vector_t<TableInfo>  privateDictInfos;
M
Michiharu Ariza 已提交
535 536

  SubrRefMaps             subrRefMaps;
537

M
Michiharu Ariza 已提交
538 539 540 541 542 543 544 545 546 547 548 549 550
  bool                    flatten_subrs;
  bool                    drop_hints;

  bool                    gid_renum;
  bool                    subset_encoding;
  uint8_t                 subset_enc_format;
  unsigned int            subset_enc_num_codes;
  hb_vector_t<code_pair>  subset_enc_code_ranges;
  hb_vector_t<code_pair>  subset_enc_supp_codes;

  uint8_t                 subset_charset_format;
  hb_vector_t<code_pair>  subset_charset_ranges;
  bool                    subset_charset;
M
Michiharu Ariza 已提交
551 552
};

553
static inline bool _write_cff1 (const cff_subset_plan &plan,
554
                                const OT::cff1::accelerator_subset_t  &acc,
M
Michiharu Ariza 已提交
555 556 557 558 559 560
                                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 已提交
561
  char RETURN_OP[1] = { OpCode_return };
M
Michiharu Ariza 已提交
562
  const ByteStr NULL_SUBR (RETURN_OP, 1);
M
Michiharu Ariza 已提交
563

564
  OT::cff1 *cff = c.start_serialize<OT::cff1> ();
M
Michiharu Ariza 已提交
565 566 567 568 569 570 571 572 573 574 575 576
  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);
577
    CFF1NameIndex *dest = c.start_embed<CFF1NameIndex> ();
M
Michiharu Ariza 已提交
578 579 580 581 582 583 584 585 586 587
    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 已提交
588
    assert (plan.offsets.topDictInfo.offset == c.head - c.start);
589
    CFF1IndexOf<TopDict> *dest = c.start_embed< CFF1IndexOf<TopDict> > ();
M
Michiharu Ariza 已提交
590
    if (dest == nullptr) return false;
591
    CFF1TopDict_OpSerializer topSzr;
M
Michiharu Ariza 已提交
592 593 594
    if (unlikely (!dest->serialize (&c, plan.offsets.topDictInfo.offSize,
                                    &plan.topdict_mod, 1,
                                    plan.topdict_sizes, topSzr, plan.offsets)))
M
Michiharu Ariza 已提交
595 596 597 598 599 600 601 602 603
    {
      DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF top dict");
      return false;
    }
  }

  /* String INDEX */
  {
    assert (plan.offsets.stringIndexOffset == c.head - c.start);
604
    CFF1StringIndex *dest = c.start_embed<CFF1StringIndex> ();
M
Michiharu Ariza 已提交
605 606 607 608 609 610 611 612 613 614
    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 已提交
615
    assert (plan.offsets.globalSubrsInfo.offset != 0);
M
Michiharu Ariza 已提交
616
    assert (plan.offsets.globalSubrsInfo.offset == c.head - c.start);
617
    CFF1Subrs *dest = c.start_embed<CFF1Subrs> ();
M
Michiharu Ariza 已提交
618
    if (unlikely (dest == nullptr)) return false;
M
Michiharu Ariza 已提交
619
    if (unlikely (!dest->serialize (&c, *acc.globalSubrs, plan.offsets.globalSubrsInfo.offSize, plan.subrRefMaps.global_map, NULL_SUBR)))
M
Michiharu Ariza 已提交
620 621 622 623 624 625 626
    {
      DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF global subrs");
      return false;
    }
  }

  /* Encoding */
M
Michiharu Ariza 已提交
627 628
  if (plan.subset_encoding)
  {
M
Michiharu Ariza 已提交
629 630 631
    assert (plan.offsets.encodingOffset == c.head - c.start);
    Encoding *dest = c.start_embed<Encoding> ();
    if (unlikely (dest == nullptr)) return false;
M
Michiharu Ariza 已提交
632 633 634 635 636
    if (unlikely (!dest->serialize (&c,
                                    plan.subset_enc_format,
                                    plan.subset_enc_num_codes,
                                    plan.subset_enc_code_ranges,
                                    plan.subset_enc_supp_codes)))
M
Michiharu Ariza 已提交
637 638 639 640 641 642 643
    {
      DEBUG_MSG (SUBSET, nullptr, "failed to serialize Encoding");
      return false;
    }
  }

  /* Charset */
M
Michiharu Ariza 已提交
644
  if (plan.subset_charset)
M
Michiharu Ariza 已提交
645 646 647 648
  {
    assert (plan.offsets.charsetOffset == c.head - c.start);
    Charset *dest = c.start_embed<Charset> ();
    if (unlikely (dest == nullptr)) return false;
M
Michiharu Ariza 已提交
649 650 651 652
    if (unlikely (!dest->serialize (&c,
                                    plan.subset_charset_format,
                                    plan.num_glyphs,
                                    plan.subset_charset_ranges)))
M
Michiharu Ariza 已提交
653 654 655 656 657 658 659
    {
      DEBUG_MSG (SUBSET, nullptr, "failed to serialize Charset");
      return false;
    }
  }

  /* FDSelect */
660
  if (acc.fdSelect != &Null(CFF1FDSelect))
M
Michiharu Ariza 已提交
661 662 663 664 665 666
  {
    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,
M
Michiharu Ariza 已提交
667 668
                                                plan.subset_fdselect_format, plan.offsets.FDSelectInfo.size,
                                                plan.subset_fdselect_first_glyphs,
M
Michiharu Ariza 已提交
669 670 671 672 673 674 675 676
                                                plan.fdmap)))
      {
        DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF subset FDSelect");
        return false;
      }
    }
    else
    {
677
      CFF1FDSelect *dest = c.start_embed<CFF1FDSelect> ();
M
Michiharu Ariza 已提交
678 679 680 681 682 683 684 685 686
      if (unlikely (!dest->serialize (&c, *acc.fdSelect, acc.num_glyphs)))
      {
        DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF FDSelect");
        return false;
      }
    }
  }

  /* FDArray (FD Index) */
687
  if (acc.fdArray != &Null(CFF1FDArray))
M
Michiharu Ariza 已提交
688
  {
M
Michiharu Ariza 已提交
689
    assert (plan.offsets.FDArrayInfo.offset == c.head - c.start);
690
    CFF1FDArray  *fda = c.start_embed<CFF1FDArray> ();
M
Michiharu Ariza 已提交
691
    if (unlikely (fda == nullptr)) return false;
M
Michiharu Ariza 已提交
692
    CFFFontDict_OpSerializer  fontSzr;
M
Michiharu Ariza 已提交
693
    if (unlikely (!fda->serialize (&c, plan.offsets.FDArrayInfo.offSize,
M
Michiharu Ariza 已提交
694
                                   acc.fontDicts, plan.subset_fdcount, plan.fdmap,
M
Michiharu Ariza 已提交
695 696 697 698 699 700 701 702 703
                                   fontSzr, plan.privateDictInfos)))
    {
      DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF FDArray");
      return false;
    }
  }

  /* CharStrings */
  {
M
Michiharu Ariza 已提交
704
    assert (plan.offsets.charStringsInfo.offset == c.head - c.start);
705
    CFF1CharStrings  *cs = c.start_embed<CFF1CharStrings> ();
M
Michiharu Ariza 已提交
706
    if (unlikely (cs == nullptr)) return false;
M
Michiharu Ariza 已提交
707
    if (unlikely (!cs->serialize (&c, plan.offsets.charStringsInfo.offSize, plan.subset_charstrings)))
M
Michiharu Ariza 已提交
708 709 710 711 712 713 714 715 716 717
    {
      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++)
  {
718
    if (!plan.fdmap.excludes (i))
M
Michiharu Ariza 已提交
719
    {
720 721
      PrivateDict  *pd = c.start_embed<PrivateDict> ();
      if (unlikely (pd == nullptr)) return false;
M
Michiharu Ariza 已提交
722
      unsigned int priv_size = plan.flatten_subrs? 0: plan.privateDictInfos[plan.fdmap[i]].size;
723
      bool result;
M
Michiharu Ariza 已提交
724
      CFFPrivateDict_OpSerializer privSzr (plan.drop_hints, plan.flatten_subrs);
725
      /* N.B. local subrs immediately follows its corresponding private dict. i.e., subr offset == private dict size */
M
Michiharu Ariza 已提交
726
      result = pd->serialize (&c, acc.privateDicts[i], privSzr, priv_size);
727
      if (unlikely (!result))
M
Michiharu Ariza 已提交
728
      {
729
        DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF Private Dict[%d]", i);
M
Michiharu Ariza 已提交
730 731
        return false;
      }
M
Michiharu Ariza 已提交
732
      if (!plan.flatten_subrs && (acc.privateDicts[i].subrsOffset != 0))
M
Michiharu Ariza 已提交
733
      {
734 735
        CFF1Subrs *subrs = c.start_embed<CFF1Subrs> ();
        if (unlikely (subrs == nullptr) || acc.privateDicts[i].localSubrs == &Null(CFF1Subrs))
736 737 738 739
        {
          DEBUG_MSG (SUBSET, nullptr, "CFF subset: local subrs unexpectedly null [%d]", i);
          return false;
        }
M
Michiharu Ariza 已提交
740
        if (unlikely (!subrs->serialize (&c, *acc.privateDicts[i].localSubrs, plan.offsets.localSubrsInfos[i].offSize, plan.subrRefMaps.local_maps[i], NULL_SUBR)))
741 742 743 744
        {
          DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF local subrs [%d]", i);
          return false;
        }
M
Michiharu Ariza 已提交
745 746 747 748
      }
    }
  }

M
Michiharu Ariza 已提交
749
  assert (c.head == c.end);
M
Michiharu Ariza 已提交
750 751 752 753 754 755
  c.end_serialize ();

  return true;
}

static bool
756
_hb_subset_cff1 (const OT::cff1::accelerator_subset_t  &acc,
M
Michiharu Ariza 已提交
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
                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);

772
  if (unlikely (!_write_cff1 (cff_plan, acc, plan->glyphs,
M
Michiharu Ariza 已提交
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
                              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;
}

/**
788
 * hb_subset_cff1:
M
Michiharu Ariza 已提交
789 790 791 792 793
 * Subsets the CFF table according to a provided plan.
 *
 * Return value: subsetted cff table.
 **/
bool
794
hb_subset_cff1 (hb_subset_plan_t *plan,
M
Michiharu Ariza 已提交
795 796
                hb_blob_t       **prime /* OUT */)
{
797
  hb_blob_t *cff_blob = hb_sanitize_context_t().reference_table<CFF::cff1> (plan->source);
M
Michiharu Ariza 已提交
798 799
  const char *data = hb_blob_get_data(cff_blob, nullptr);

800
  OT::cff1::accelerator_subset_t acc;
M
Michiharu Ariza 已提交
801 802
  acc.init(plan->source);
  bool result = likely (acc.is_valid ()) &&
803
                        _hb_subset_cff1 (acc, data, plan, prime);
M
Michiharu Ariza 已提交
804 805 806 807 808
  hb_blob_destroy (cff_blob);
  acc.fini ();

  return result;
}