gfx/skia/trunk/src/pdf/SkPDFFont.cpp

Sat, 03 Jan 2015 20:18:00 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Sat, 03 Jan 2015 20:18:00 +0100
branch
TOR_BUG_3246
changeset 7
129ffea94266
permissions
-rw-r--r--

Conditionally enable double key logic according to:
private browsing mode or privacy.thirdparty.isolate preference and
implement in GetCookieStringCommon and FindCookie where it counts...
With some reservations of how to convince FindCookie users to test
condition and pass a nullptr when disabling double key logic.

     1 /*
     2  * Copyright 2011 Google Inc.
     3  *
     4  * Use of this source code is governed by a BSD-style license that can be
     5  * found in the LICENSE file.
     6  */
     8 #include <ctype.h>
    10 #include "SkData.h"
    11 #include "SkFontHost.h"
    12 #include "SkGlyphCache.h"
    13 #include "SkPaint.h"
    14 #include "SkPDFCatalog.h"
    15 #include "SkPDFDevice.h"
    16 #include "SkPDFFont.h"
    17 #include "SkPDFFontImpl.h"
    18 #include "SkPDFStream.h"
    19 #include "SkPDFTypes.h"
    20 #include "SkPDFUtils.h"
    21 #include "SkRefCnt.h"
    22 #include "SkScalar.h"
    23 #include "SkStream.h"
    24 #include "SkTypefacePriv.h"
    25 #include "SkTypes.h"
    26 #include "SkUtils.h"
    28 #if defined (SK_SFNTLY_SUBSETTER)
    29 #include SK_SFNTLY_SUBSETTER
    30 #endif
    32 // PDF's notion of symbolic vs non-symbolic is related to the character set, not
    33 // symbols vs. characters.  Rarely is a font the right character set to call it
    34 // non-symbolic, so always call it symbolic.  (PDF 1.4 spec, section 5.7.1)
    35 static const int kPdfSymbolic = 4;
    37 namespace {
    39 ///////////////////////////////////////////////////////////////////////////////
    40 // File-Local Functions
    41 ///////////////////////////////////////////////////////////////////////////////
    43 bool parsePFBSection(const uint8_t** src, size_t* len, int sectionType,
    44                      size_t* size) {
    45     // PFB sections have a two or six bytes header. 0x80 and a one byte
    46     // section type followed by a four byte section length.  Type one is
    47     // an ASCII section (includes a length), type two is a binary section
    48     // (includes a length) and type three is an EOF marker with no length.
    49     const uint8_t* buf = *src;
    50     if (*len < 2 || buf[0] != 0x80 || buf[1] != sectionType) {
    51         return false;
    52     } else if (buf[1] == 3) {
    53         return true;
    54     } else if (*len < 6) {
    55         return false;
    56     }
    58     *size = (size_t)buf[2] | ((size_t)buf[3] << 8) | ((size_t)buf[4] << 16) |
    59             ((size_t)buf[5] << 24);
    60     size_t consumed = *size + 6;
    61     if (consumed > *len) {
    62         return false;
    63     }
    64     *src = *src + consumed;
    65     *len = *len - consumed;
    66     return true;
    67 }
    69 bool parsePFB(const uint8_t* src, size_t size, size_t* headerLen,
    70               size_t* dataLen, size_t* trailerLen) {
    71     const uint8_t* srcPtr = src;
    72     size_t remaining = size;
    74     return parsePFBSection(&srcPtr, &remaining, 1, headerLen) &&
    75            parsePFBSection(&srcPtr, &remaining, 2, dataLen) &&
    76            parsePFBSection(&srcPtr, &remaining, 1, trailerLen) &&
    77            parsePFBSection(&srcPtr, &remaining, 3, NULL);
    78 }
    80 /* The sections of a PFA file are implicitly defined.  The body starts
    81  * after the line containing "eexec," and the trailer starts with 512
    82  * literal 0's followed by "cleartomark" (plus arbitrary white space).
    83  *
    84  * This function assumes that src is NUL terminated, but the NUL
    85  * termination is not included in size.
    86  *
    87  */
    88 bool parsePFA(const char* src, size_t size, size_t* headerLen,
    89               size_t* hexDataLen, size_t* dataLen, size_t* trailerLen) {
    90     const char* end = src + size;
    92     const char* dataPos = strstr(src, "eexec");
    93     if (!dataPos) {
    94         return false;
    95     }
    96     dataPos += strlen("eexec");
    97     while ((*dataPos == '\n' || *dataPos == '\r' || *dataPos == ' ') &&
    98             dataPos < end) {
    99         dataPos++;
   100     }
   101     *headerLen = dataPos - src;
   103     const char* trailerPos = strstr(dataPos, "cleartomark");
   104     if (!trailerPos) {
   105         return false;
   106     }
   107     int zeroCount = 0;
   108     for (trailerPos--; trailerPos > dataPos && zeroCount < 512; trailerPos--) {
   109         if (*trailerPos == '\n' || *trailerPos == '\r' || *trailerPos == ' ') {
   110             continue;
   111         } else if (*trailerPos == '0') {
   112             zeroCount++;
   113         } else {
   114             return false;
   115         }
   116     }
   117     if (zeroCount != 512) {
   118         return false;
   119     }
   121     *hexDataLen = trailerPos - src - *headerLen;
   122     *trailerLen = size - *headerLen - *hexDataLen;
   124     // Verify that the data section is hex encoded and count the bytes.
   125     int nibbles = 0;
   126     for (; dataPos < trailerPos; dataPos++) {
   127         if (isspace(*dataPos)) {
   128             continue;
   129         }
   130         if (!isxdigit(*dataPos)) {
   131             return false;
   132         }
   133         nibbles++;
   134     }
   135     *dataLen = (nibbles + 1) / 2;
   137     return true;
   138 }
   140 int8_t hexToBin(uint8_t c) {
   141     if (!isxdigit(c)) {
   142         return -1;
   143     } else if (c <= '9') {
   144         return c - '0';
   145     } else if (c <= 'F') {
   146         return c - 'A' + 10;
   147     } else if (c <= 'f') {
   148         return c - 'a' + 10;
   149     }
   150     return -1;
   151 }
   153 SkStream* handleType1Stream(SkStream* srcStream, size_t* headerLen,
   154                             size_t* dataLen, size_t* trailerLen) {
   155     // srcStream may be backed by a file or a unseekable fd, so we may not be
   156     // able to use skip(), rewind(), or getMemoryBase().  read()ing through
   157     // the input only once is doable, but very ugly. Furthermore, it'd be nice
   158     // if the data was NUL terminated so that we can use strstr() to search it.
   159     // Make as few copies as possible given these constraints.
   160     SkDynamicMemoryWStream dynamicStream;
   161     SkAutoTUnref<SkMemoryStream> staticStream;
   162     SkData* data = NULL;
   163     const uint8_t* src;
   164     size_t srcLen;
   165     if ((srcLen = srcStream->getLength()) > 0) {
   166         staticStream.reset(new SkMemoryStream(srcLen + 1));
   167         src = (const uint8_t*)staticStream->getMemoryBase();
   168         if (srcStream->getMemoryBase() != NULL) {
   169             memcpy((void *)src, srcStream->getMemoryBase(), srcLen);
   170         } else {
   171             size_t read = 0;
   172             while (read < srcLen) {
   173                 size_t got = srcStream->read((void *)staticStream->getAtPos(),
   174                                              srcLen - read);
   175                 if (got == 0) {
   176                     return NULL;
   177                 }
   178                 read += got;
   179                 staticStream->seek(read);
   180             }
   181         }
   182         ((uint8_t *)src)[srcLen] = 0;
   183     } else {
   184         static const size_t kBufSize = 4096;
   185         uint8_t buf[kBufSize];
   186         size_t amount;
   187         while ((amount = srcStream->read(buf, kBufSize)) > 0) {
   188             dynamicStream.write(buf, amount);
   189         }
   190         amount = 0;
   191         dynamicStream.write(&amount, 1);  // NULL terminator.
   192         data = dynamicStream.copyToData();
   193         src = data->bytes();
   194         srcLen = data->size() - 1;
   195     }
   197     // this handles releasing the data we may have gotten from dynamicStream.
   198     // if data is null, it is a no-op
   199     SkAutoDataUnref aud(data);
   201     if (parsePFB(src, srcLen, headerLen, dataLen, trailerLen)) {
   202         SkMemoryStream* result =
   203             new SkMemoryStream(*headerLen + *dataLen + *trailerLen);
   204         memcpy((char*)result->getAtPos(), src + 6, *headerLen);
   205         result->seek(*headerLen);
   206         memcpy((char*)result->getAtPos(), src + 6 + *headerLen + 6, *dataLen);
   207         result->seek(*headerLen + *dataLen);
   208         memcpy((char*)result->getAtPos(), src + 6 + *headerLen + 6 + *dataLen,
   209                *trailerLen);
   210         result->rewind();
   211         return result;
   212     }
   214     // A PFA has to be converted for PDF.
   215     size_t hexDataLen;
   216     if (parsePFA((const char*)src, srcLen, headerLen, &hexDataLen, dataLen,
   217                  trailerLen)) {
   218         SkMemoryStream* result =
   219             new SkMemoryStream(*headerLen + *dataLen + *trailerLen);
   220         memcpy((char*)result->getAtPos(), src, *headerLen);
   221         result->seek(*headerLen);
   223         const uint8_t* hexData = src + *headerLen;
   224         const uint8_t* trailer = hexData + hexDataLen;
   225         size_t outputOffset = 0;
   226         uint8_t dataByte = 0;  // To hush compiler.
   227         bool highNibble = true;
   228         for (; hexData < trailer; hexData++) {
   229             int8_t curNibble = hexToBin(*hexData);
   230             if (curNibble < 0) {
   231                 continue;
   232             }
   233             if (highNibble) {
   234                 dataByte = curNibble << 4;
   235                 highNibble = false;
   236             } else {
   237                 dataByte |= curNibble;
   238                 highNibble = true;
   239                 ((char *)result->getAtPos())[outputOffset++] = dataByte;
   240             }
   241         }
   242         if (!highNibble) {
   243             ((char *)result->getAtPos())[outputOffset++] = dataByte;
   244         }
   245         SkASSERT(outputOffset == *dataLen);
   246         result->seek(*headerLen + outputOffset);
   248         memcpy((char *)result->getAtPos(), src + *headerLen + hexDataLen,
   249                *trailerLen);
   250         result->rewind();
   251         return result;
   252     }
   254     return NULL;
   255 }
   257 // scale from em-units to base-1000, returning as a SkScalar
   258 SkScalar scaleFromFontUnits(int16_t val, uint16_t emSize) {
   259     SkScalar scaled = SkIntToScalar(val);
   260     if (emSize == 1000) {
   261         return scaled;
   262     } else {
   263         return SkScalarMulDiv(scaled, 1000, emSize);
   264     }
   265 }
   267 void setGlyphWidthAndBoundingBox(SkScalar width, SkIRect box,
   268                                  SkWStream* content) {
   269     // Specify width and bounding box for the glyph.
   270     SkPDFScalar::Append(width, content);
   271     content->writeText(" 0 ");
   272     content->writeDecAsText(box.fLeft);
   273     content->writeText(" ");
   274     content->writeDecAsText(box.fTop);
   275     content->writeText(" ");
   276     content->writeDecAsText(box.fRight);
   277     content->writeText(" ");
   278     content->writeDecAsText(box.fBottom);
   279     content->writeText(" d1\n");
   280 }
   282 SkPDFArray* makeFontBBox(SkIRect glyphBBox, uint16_t emSize) {
   283     SkPDFArray* bbox = new SkPDFArray;
   284     bbox->reserve(4);
   285     bbox->appendScalar(scaleFromFontUnits(glyphBBox.fLeft, emSize));
   286     bbox->appendScalar(scaleFromFontUnits(glyphBBox.fBottom, emSize));
   287     bbox->appendScalar(scaleFromFontUnits(glyphBBox.fRight, emSize));
   288     bbox->appendScalar(scaleFromFontUnits(glyphBBox.fTop, emSize));
   289     return bbox;
   290 }
   292 SkPDFArray* appendWidth(const int16_t& width, uint16_t emSize,
   293                         SkPDFArray* array) {
   294     array->appendScalar(scaleFromFontUnits(width, emSize));
   295     return array;
   296 }
   298 SkPDFArray* appendVerticalAdvance(
   299         const SkAdvancedTypefaceMetrics::VerticalMetric& advance,
   300         uint16_t emSize, SkPDFArray* array) {
   301     appendWidth(advance.fVerticalAdvance, emSize, array);
   302     appendWidth(advance.fOriginXDisp, emSize, array);
   303     appendWidth(advance.fOriginYDisp, emSize, array);
   304     return array;
   305 }
   307 template <typename Data>
   308 SkPDFArray* composeAdvanceData(
   309         SkAdvancedTypefaceMetrics::AdvanceMetric<Data>* advanceInfo,
   310         uint16_t emSize,
   311         SkPDFArray* (*appendAdvance)(const Data& advance, uint16_t emSize,
   312                                      SkPDFArray* array),
   313         Data* defaultAdvance) {
   314     SkPDFArray* result = new SkPDFArray();
   315     for (; advanceInfo != NULL; advanceInfo = advanceInfo->fNext.get()) {
   316         switch (advanceInfo->fType) {
   317             case SkAdvancedTypefaceMetrics::WidthRange::kDefault: {
   318                 SkASSERT(advanceInfo->fAdvance.count() == 1);
   319                 *defaultAdvance = advanceInfo->fAdvance[0];
   320                 break;
   321             }
   322             case SkAdvancedTypefaceMetrics::WidthRange::kRange: {
   323                 SkAutoTUnref<SkPDFArray> advanceArray(new SkPDFArray());
   324                 for (int j = 0; j < advanceInfo->fAdvance.count(); j++)
   325                     appendAdvance(advanceInfo->fAdvance[j], emSize,
   326                                   advanceArray.get());
   327                 result->appendInt(advanceInfo->fStartId);
   328                 result->append(advanceArray.get());
   329                 break;
   330             }
   331             case SkAdvancedTypefaceMetrics::WidthRange::kRun: {
   332                 SkASSERT(advanceInfo->fAdvance.count() == 1);
   333                 result->appendInt(advanceInfo->fStartId);
   334                 result->appendInt(advanceInfo->fEndId);
   335                 appendAdvance(advanceInfo->fAdvance[0], emSize, result);
   336                 break;
   337             }
   338         }
   339     }
   340     return result;
   341 }
   343 }  // namespace
   345 static void append_tounicode_header(SkDynamicMemoryWStream* cmap,
   346                                     uint16_t firstGlyphID,
   347                                     uint16_t lastGlyphID) {
   348     // 12 dict begin: 12 is an Adobe-suggested value. Shall not change.
   349     // It's there to prevent old version Adobe Readers from malfunctioning.
   350     const char* kHeader =
   351         "/CIDInit /ProcSet findresource begin\n"
   352         "12 dict begin\n"
   353         "begincmap\n";
   354     cmap->writeText(kHeader);
   356     // The /CIDSystemInfo must be consistent to the one in
   357     // SkPDFFont::populateCIDFont().
   358     // We can not pass over the system info object here because the format is
   359     // different. This is not a reference object.
   360     const char* kSysInfo =
   361         "/CIDSystemInfo\n"
   362         "<<  /Registry (Adobe)\n"
   363         "/Ordering (UCS)\n"
   364         "/Supplement 0\n"
   365         ">> def\n";
   366     cmap->writeText(kSysInfo);
   368     // The CMapName must be consistent to /CIDSystemInfo above.
   369     // /CMapType 2 means ToUnicode.
   370     // Codespace range just tells the PDF processor the valid range.
   371     const char* kTypeInfoHeader =
   372         "/CMapName /Adobe-Identity-UCS def\n"
   373         "/CMapType 2 def\n"
   374         "1 begincodespacerange\n";
   375     cmap->writeText(kTypeInfoHeader);
   377     // e.g.     "<0000> <FFFF>\n"
   378     SkString range;
   379     range.appendf("<%04X> <%04X>\n", firstGlyphID, lastGlyphID);
   380     cmap->writeText(range.c_str());
   382     const char* kTypeInfoFooter = "endcodespacerange\n";
   383     cmap->writeText(kTypeInfoFooter);
   384 }
   386 static void append_cmap_footer(SkDynamicMemoryWStream* cmap) {
   387     const char* kFooter =
   388         "endcmap\n"
   389         "CMapName currentdict /CMap defineresource pop\n"
   390         "end\n"
   391         "end";
   392     cmap->writeText(kFooter);
   393 }
   395 struct BFChar {
   396     uint16_t fGlyphId;
   397     SkUnichar fUnicode;
   398 };
   400 struct BFRange {
   401     uint16_t fStart;
   402     uint16_t fEnd;
   403     SkUnichar fUnicode;
   404 };
   406 static void append_bfchar_section(const SkTDArray<BFChar>& bfchar,
   407                                   SkDynamicMemoryWStream* cmap) {
   408     // PDF spec defines that every bf* list can have at most 100 entries.
   409     for (int i = 0; i < bfchar.count(); i += 100) {
   410         int count = bfchar.count() - i;
   411         count = SkMin32(count, 100);
   412         cmap->writeDecAsText(count);
   413         cmap->writeText(" beginbfchar\n");
   414         for (int j = 0; j < count; ++j) {
   415             cmap->writeText("<");
   416             cmap->writeHexAsText(bfchar[i + j].fGlyphId, 4);
   417             cmap->writeText("> <");
   418             cmap->writeHexAsText(bfchar[i + j].fUnicode, 4);
   419             cmap->writeText(">\n");
   420         }
   421         cmap->writeText("endbfchar\n");
   422     }
   423 }
   425 static void append_bfrange_section(const SkTDArray<BFRange>& bfrange,
   426                                    SkDynamicMemoryWStream* cmap) {
   427     // PDF spec defines that every bf* list can have at most 100 entries.
   428     for (int i = 0; i < bfrange.count(); i += 100) {
   429         int count = bfrange.count() - i;
   430         count = SkMin32(count, 100);
   431         cmap->writeDecAsText(count);
   432         cmap->writeText(" beginbfrange\n");
   433         for (int j = 0; j < count; ++j) {
   434             cmap->writeText("<");
   435             cmap->writeHexAsText(bfrange[i + j].fStart, 4);
   436             cmap->writeText("> <");
   437             cmap->writeHexAsText(bfrange[i + j].fEnd, 4);
   438             cmap->writeText("> <");
   439             cmap->writeHexAsText(bfrange[i + j].fUnicode, 4);
   440             cmap->writeText(">\n");
   441         }
   442         cmap->writeText("endbfrange\n");
   443     }
   444 }
   446 // Generate <bfchar> and <bfrange> table according to PDF spec 1.4 and Adobe
   447 // Technote 5014.
   448 // The function is not static so we can test it in unit tests.
   449 //
   450 // Current implementation guarantees bfchar and bfrange entries do not overlap.
   451 //
   452 // Current implementation does not attempt aggresive optimizations against
   453 // following case because the specification is not clear.
   454 //
   455 // 4 beginbfchar          1 beginbfchar
   456 // <0003> <0013>          <0020> <0014>
   457 // <0005> <0015>    to    endbfchar
   458 // <0007> <0017>          1 beginbfrange
   459 // <0020> <0014>          <0003> <0007> <0013>
   460 // endbfchar              endbfrange
   461 //
   462 // Adobe Technote 5014 said: "Code mappings (unlike codespace ranges) may
   463 // overlap, but succeeding maps supersede preceding maps."
   464 //
   465 // In case of searching text in PDF, bfrange will have higher precedence so
   466 // typing char id 0x0014 in search box will get glyph id 0x0004 first.  However,
   467 // the spec does not mention how will this kind of conflict being resolved.
   468 //
   469 // For the worst case (having 65536 continuous unicode and we use every other
   470 // one of them), the possible savings by aggressive optimization is 416KB
   471 // pre-compressed and does not provide enough motivation for implementation.
   473 // FIXME: this should be in a header so that it is separately testable
   474 // ( see caller in tests/ToUnicode.cpp )
   475 void append_cmap_sections(const SkTDArray<SkUnichar>& glyphToUnicode,
   476                           const SkPDFGlyphSet* subset,
   477                           SkDynamicMemoryWStream* cmap,
   478                           bool multiByteGlyphs,
   479                           uint16_t firstGlyphID,
   480                           uint16_t lastGlyphID);
   482 void append_cmap_sections(const SkTDArray<SkUnichar>& glyphToUnicode,
   483                           const SkPDFGlyphSet* subset,
   484                           SkDynamicMemoryWStream* cmap,
   485                           bool multiByteGlyphs,
   486                           uint16_t firstGlyphID,
   487                           uint16_t lastGlyphID) {
   488     if (glyphToUnicode.isEmpty()) {
   489         return;
   490     }
   491     int glyphOffset = 0;
   492     if (!multiByteGlyphs) {
   493         glyphOffset = firstGlyphID - 1;
   494     }
   496     SkTDArray<BFChar> bfcharEntries;
   497     SkTDArray<BFRange> bfrangeEntries;
   499     BFRange currentRangeEntry = {0, 0, 0};
   500     bool rangeEmpty = true;
   501     const int limit =
   502             SkMin32(lastGlyphID + 1, glyphToUnicode.count()) - glyphOffset;
   504     for (int i = firstGlyphID - glyphOffset; i < limit + 1; ++i) {
   505         bool inSubset = i < limit &&
   506                         (subset == NULL || subset->has(i + glyphOffset));
   507         if (!rangeEmpty) {
   508             // PDF spec requires bfrange not changing the higher byte,
   509             // e.g. <1035> <10FF> <2222> is ok, but
   510             //      <1035> <1100> <2222> is no good
   511             bool inRange =
   512                 i == currentRangeEntry.fEnd + 1 &&
   513                 i >> 8 == currentRangeEntry.fStart >> 8 &&
   514                 i < limit &&
   515                 glyphToUnicode[i + glyphOffset] ==
   516                     currentRangeEntry.fUnicode + i - currentRangeEntry.fStart;
   517             if (!inSubset || !inRange) {
   518                 if (currentRangeEntry.fEnd > currentRangeEntry.fStart) {
   519                     bfrangeEntries.push(currentRangeEntry);
   520                 } else {
   521                     BFChar* entry = bfcharEntries.append();
   522                     entry->fGlyphId = currentRangeEntry.fStart;
   523                     entry->fUnicode = currentRangeEntry.fUnicode;
   524                 }
   525                 rangeEmpty = true;
   526             }
   527         }
   528         if (inSubset) {
   529             currentRangeEntry.fEnd = i;
   530             if (rangeEmpty) {
   531               currentRangeEntry.fStart = i;
   532               currentRangeEntry.fUnicode = glyphToUnicode[i + glyphOffset];
   533               rangeEmpty = false;
   534             }
   535         }
   536     }
   538     // The spec requires all bfchar entries for a font must come before bfrange
   539     // entries.
   540     append_bfchar_section(bfcharEntries, cmap);
   541     append_bfrange_section(bfrangeEntries, cmap);
   542 }
   544 static SkPDFStream* generate_tounicode_cmap(
   545         const SkTDArray<SkUnichar>& glyphToUnicode,
   546         const SkPDFGlyphSet* subset,
   547         bool multiByteGlyphs,
   548         uint16_t firstGlyphID,
   549         uint16_t lastGlyphID) {
   550     SkDynamicMemoryWStream cmap;
   551     if (multiByteGlyphs) {
   552         append_tounicode_header(&cmap, firstGlyphID, lastGlyphID);
   553     } else {
   554         append_tounicode_header(&cmap, 1, lastGlyphID - firstGlyphID + 1);
   555     }
   556     append_cmap_sections(glyphToUnicode, subset, &cmap, multiByteGlyphs,
   557                          firstGlyphID, lastGlyphID);
   558     append_cmap_footer(&cmap);
   559     SkAutoTUnref<SkMemoryStream> cmapStream(new SkMemoryStream());
   560     cmapStream->setData(cmap.copyToData())->unref();
   561     return new SkPDFStream(cmapStream.get());
   562 }
   564 #if defined (SK_SFNTLY_SUBSETTER)
   565 static void sk_delete_array(const void* ptr, size_t, void*) {
   566     // Use C-style cast to cast away const and cast type simultaneously.
   567     delete[] (unsigned char*)ptr;
   568 }
   569 #endif
   571 static int get_subset_font_stream(const char* fontName,
   572                                   const SkTypeface* typeface,
   573                                   const SkTDArray<uint32_t>& subset,
   574                                   SkPDFStream** fontStream) {
   575     int ttcIndex;
   576     SkAutoTUnref<SkStream> fontData(typeface->openStream(&ttcIndex));
   578     int fontSize = fontData->getLength();
   580 #if defined (SK_SFNTLY_SUBSETTER)
   581     // Read font into buffer.
   582     SkPDFStream* subsetFontStream = NULL;
   583     SkTDArray<unsigned char> originalFont;
   584     originalFont.setCount(fontSize);
   585     if (fontData->read(originalFont.begin(), fontSize) == (size_t)fontSize) {
   586         unsigned char* subsetFont = NULL;
   587         // sfntly requires unsigned int* to be passed in, as far as we know,
   588         // unsigned int is equivalent to uint32_t on all platforms.
   589         SK_COMPILE_ASSERT(sizeof(unsigned int) == sizeof(uint32_t),
   590                           unsigned_int_not_32_bits);
   591         int subsetFontSize = SfntlyWrapper::SubsetFont(fontName,
   592                                                        originalFont.begin(),
   593                                                        fontSize,
   594                                                        subset.begin(),
   595                                                        subset.count(),
   596                                                        &subsetFont);
   597         if (subsetFontSize > 0 && subsetFont != NULL) {
   598             SkAutoDataUnref data(SkData::NewWithProc(subsetFont,
   599                                                      subsetFontSize,
   600                                                      sk_delete_array,
   601                                                      NULL));
   602             subsetFontStream = new SkPDFStream(data.get());
   603             fontSize = subsetFontSize;
   604         }
   605     }
   606     if (subsetFontStream) {
   607         *fontStream = subsetFontStream;
   608         return fontSize;
   609     }
   610     fontData->rewind();
   611 #else
   612     sk_ignore_unused_variable(fontName);
   613     sk_ignore_unused_variable(subset);
   614 #endif
   616     // Fail over: just embed the whole font.
   617     *fontStream = new SkPDFStream(fontData.get());
   618     return fontSize;
   619 }
   621 ///////////////////////////////////////////////////////////////////////////////
   622 // class SkPDFGlyphSet
   623 ///////////////////////////////////////////////////////////////////////////////
   625 SkPDFGlyphSet::SkPDFGlyphSet() : fBitSet(SK_MaxU16 + 1) {
   626 }
   628 void SkPDFGlyphSet::set(const uint16_t* glyphIDs, int numGlyphs) {
   629     for (int i = 0; i < numGlyphs; ++i) {
   630         fBitSet.setBit(glyphIDs[i], true);
   631     }
   632 }
   634 bool SkPDFGlyphSet::has(uint16_t glyphID) const {
   635     return fBitSet.isBitSet(glyphID);
   636 }
   638 void SkPDFGlyphSet::merge(const SkPDFGlyphSet& usage) {
   639     fBitSet.orBits(usage.fBitSet);
   640 }
   642 void SkPDFGlyphSet::exportTo(SkTDArray<unsigned int>* glyphIDs) const {
   643     fBitSet.exportTo(glyphIDs);
   644 }
   646 ///////////////////////////////////////////////////////////////////////////////
   647 // class SkPDFGlyphSetMap
   648 ///////////////////////////////////////////////////////////////////////////////
   649 SkPDFGlyphSetMap::FontGlyphSetPair::FontGlyphSetPair(SkPDFFont* font,
   650                                                      SkPDFGlyphSet* glyphSet)
   651         : fFont(font),
   652           fGlyphSet(glyphSet) {
   653 }
   655 SkPDFGlyphSetMap::F2BIter::F2BIter(const SkPDFGlyphSetMap& map) {
   656     reset(map);
   657 }
   659 const SkPDFGlyphSetMap::FontGlyphSetPair* SkPDFGlyphSetMap::F2BIter::next() const {
   660     if (fIndex >= fMap->count()) {
   661         return NULL;
   662     }
   663     return &((*fMap)[fIndex++]);
   664 }
   666 void SkPDFGlyphSetMap::F2BIter::reset(const SkPDFGlyphSetMap& map) {
   667     fMap = &(map.fMap);
   668     fIndex = 0;
   669 }
   671 SkPDFGlyphSetMap::SkPDFGlyphSetMap() {
   672 }
   674 SkPDFGlyphSetMap::~SkPDFGlyphSetMap() {
   675     reset();
   676 }
   678 void SkPDFGlyphSetMap::merge(const SkPDFGlyphSetMap& usage) {
   679     for (int i = 0; i < usage.fMap.count(); ++i) {
   680         SkPDFGlyphSet* myUsage = getGlyphSetForFont(usage.fMap[i].fFont);
   681         myUsage->merge(*(usage.fMap[i].fGlyphSet));
   682     }
   683 }
   685 void SkPDFGlyphSetMap::reset() {
   686     for (int i = 0; i < fMap.count(); ++i) {
   687         delete fMap[i].fGlyphSet;  // Should not be NULL.
   688     }
   689     fMap.reset();
   690 }
   692 void SkPDFGlyphSetMap::noteGlyphUsage(SkPDFFont* font, const uint16_t* glyphIDs,
   693                                       int numGlyphs) {
   694     SkPDFGlyphSet* subset = getGlyphSetForFont(font);
   695     if (subset) {
   696         subset->set(glyphIDs, numGlyphs);
   697     }
   698 }
   700 SkPDFGlyphSet* SkPDFGlyphSetMap::getGlyphSetForFont(SkPDFFont* font) {
   701     int index = fMap.count();
   702     for (int i = 0; i < index; ++i) {
   703         if (fMap[i].fFont == font) {
   704             return fMap[i].fGlyphSet;
   705         }
   706     }
   707     fMap.append();
   708     index = fMap.count() - 1;
   709     fMap[index].fFont = font;
   710     fMap[index].fGlyphSet = new SkPDFGlyphSet();
   711     return fMap[index].fGlyphSet;
   712 }
   714 ///////////////////////////////////////////////////////////////////////////////
   715 // class SkPDFFont
   716 ///////////////////////////////////////////////////////////////////////////////
   718 /* Font subset design: It would be nice to be able to subset fonts
   719  * (particularly type 3 fonts), but it's a lot of work and not a priority.
   720  *
   721  * Resources are canonicalized and uniqueified by pointer so there has to be
   722  * some additional state indicating which subset of the font is used.  It
   723  * must be maintained at the page granularity and then combined at the document
   724  * granularity. a) change SkPDFFont to fill in its state on demand, kind of
   725  * like SkPDFGraphicState.  b) maintain a per font glyph usage class in each
   726  * page/pdf device. c) in the document, retrieve the per font glyph usage
   727  * from each page and combine it and ask for a resource with that subset.
   728  */
   730 SkPDFFont::~SkPDFFont() {
   731     SkAutoMutexAcquire lock(CanonicalFontsMutex());
   732     int index = -1;
   733     for (int i = 0 ; i < CanonicalFonts().count() ; i++) {
   734         if (CanonicalFonts()[i].fFont == this) {
   735             index = i;
   736         }
   737     }
   739     SkDEBUGCODE(int indexFound;)
   740     SkASSERT(index == -1 ||
   741              (Find(fTypeface->uniqueID(),
   742                    fFirstGlyphID,
   743                    &indexFound) &&
   744              index == indexFound));
   745     if (index >= 0) {
   746         CanonicalFonts().removeShuffle(index);
   747     }
   748     fResources.unrefAll();
   749 }
   751 void SkPDFFont::getResources(const SkTSet<SkPDFObject*>& knownResourceObjects,
   752                              SkTSet<SkPDFObject*>* newResourceObjects) {
   753     GetResourcesHelper(&fResources, knownResourceObjects, newResourceObjects);
   754 }
   756 SkTypeface* SkPDFFont::typeface() {
   757     return fTypeface.get();
   758 }
   760 SkAdvancedTypefaceMetrics::FontType SkPDFFont::getType() {
   761     return fFontType;
   762 }
   764 bool SkPDFFont::hasGlyph(uint16_t id) {
   765     return (id >= fFirstGlyphID && id <= fLastGlyphID) || id == 0;
   766 }
   768 size_t SkPDFFont::glyphsToPDFFontEncoding(uint16_t* glyphIDs,
   769                                           size_t numGlyphs) {
   770     // A font with multibyte glyphs will support all glyph IDs in a single font.
   771     if (this->multiByteGlyphs()) {
   772         return numGlyphs;
   773     }
   775     for (size_t i = 0; i < numGlyphs; i++) {
   776         if (glyphIDs[i] == 0) {
   777             continue;
   778         }
   779         if (glyphIDs[i] < fFirstGlyphID || glyphIDs[i] > fLastGlyphID) {
   780             return i;
   781         }
   782         glyphIDs[i] -= (fFirstGlyphID - 1);
   783     }
   785     return numGlyphs;
   786 }
   788 // static
   789 SkPDFFont* SkPDFFont::GetFontResource(SkTypeface* typeface, uint16_t glyphID) {
   790     SkAutoMutexAcquire lock(CanonicalFontsMutex());
   792     SkAutoResolveDefaultTypeface autoResolve(typeface);
   793     typeface = autoResolve.get();
   795     const uint32_t fontID = typeface->uniqueID();
   796     int relatedFontIndex;
   797     if (Find(fontID, glyphID, &relatedFontIndex)) {
   798         CanonicalFonts()[relatedFontIndex].fFont->ref();
   799         return CanonicalFonts()[relatedFontIndex].fFont;
   800     }
   802     SkAutoTUnref<SkAdvancedTypefaceMetrics> fontMetrics;
   803     SkPDFDict* relatedFontDescriptor = NULL;
   804     if (relatedFontIndex >= 0) {
   805         SkPDFFont* relatedFont = CanonicalFonts()[relatedFontIndex].fFont;
   806         fontMetrics.reset(relatedFont->fontInfo());
   807         SkSafeRef(fontMetrics.get());
   808         relatedFontDescriptor = relatedFont->getFontDescriptor();
   810         // This only is to catch callers who pass invalid glyph ids.
   811         // If glyph id is invalid, then we will create duplicate entries
   812         // for True Type fonts.
   813         SkAdvancedTypefaceMetrics::FontType fontType =
   814             fontMetrics.get() ? fontMetrics.get()->fType :
   815                                 SkAdvancedTypefaceMetrics::kOther_Font;
   817         if (fontType == SkAdvancedTypefaceMetrics::kType1CID_Font ||
   818             fontType == SkAdvancedTypefaceMetrics::kTrueType_Font) {
   819             CanonicalFonts()[relatedFontIndex].fFont->ref();
   820             return CanonicalFonts()[relatedFontIndex].fFont;
   821         }
   822     } else {
   823         SkAdvancedTypefaceMetrics::PerGlyphInfo info;
   824         info = SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo;
   825         info = SkTBitOr<SkAdvancedTypefaceMetrics::PerGlyphInfo>(
   826                   info, SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo);
   827 #if !defined (SK_SFNTLY_SUBSETTER)
   828         info = SkTBitOr<SkAdvancedTypefaceMetrics::PerGlyphInfo>(
   829                   info, SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo);
   830 #endif
   831         fontMetrics.reset(
   832             typeface->getAdvancedTypefaceMetrics(info, NULL, 0));
   833 #if defined (SK_SFNTLY_SUBSETTER)
   834         if (fontMetrics.get() &&
   835             fontMetrics->fType != SkAdvancedTypefaceMetrics::kTrueType_Font) {
   836             // Font does not support subsetting, get new info with advance.
   837             info = SkTBitOr<SkAdvancedTypefaceMetrics::PerGlyphInfo>(
   838                       info, SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo);
   839             fontMetrics.reset(
   840                 typeface->getAdvancedTypefaceMetrics(info, NULL, 0));
   841         }
   842 #endif
   843     }
   845     SkPDFFont* font = Create(fontMetrics.get(), typeface, glyphID,
   846                              relatedFontDescriptor);
   847     FontRec newEntry(font, fontID, font->fFirstGlyphID);
   848     CanonicalFonts().push(newEntry);
   849     return font;  // Return the reference new SkPDFFont() created.
   850 }
   852 SkPDFFont* SkPDFFont::getFontSubset(const SkPDFGlyphSet*) {
   853     return NULL;  // Default: no support.
   854 }
   856 // static
   857 SkTDArray<SkPDFFont::FontRec>& SkPDFFont::CanonicalFonts() {
   858     // This initialization is only thread safe with gcc.
   859     static SkTDArray<FontRec> gCanonicalFonts;
   860     return gCanonicalFonts;
   861 }
   863 // static
   864 SkBaseMutex& SkPDFFont::CanonicalFontsMutex() {
   865     // This initialization is only thread safe with gcc, or when
   866     // POD-style mutex initialization is used.
   867     SK_DECLARE_STATIC_MUTEX(gCanonicalFontsMutex);
   868     return gCanonicalFontsMutex;
   869 }
   871 // static
   872 bool SkPDFFont::Find(uint32_t fontID, uint16_t glyphID, int* index) {
   873     // TODO(vandebo): Optimize this, do only one search?
   874     FontRec search(NULL, fontID, glyphID);
   875     *index = CanonicalFonts().find(search);
   876     if (*index >= 0) {
   877         return true;
   878     }
   879     search.fGlyphID = 0;
   880     *index = CanonicalFonts().find(search);
   881     return false;
   882 }
   884 SkPDFFont::SkPDFFont(SkAdvancedTypefaceMetrics* info, SkTypeface* typeface,
   885                      SkPDFDict* relatedFontDescriptor)
   886         : SkPDFDict("Font"),
   887           fTypeface(ref_or_default(typeface)),
   888           fFirstGlyphID(1),
   889           fLastGlyphID(info ? info->fLastGlyphID : 0),
   890           fFontInfo(SkSafeRef(info)),
   891           fDescriptor(SkSafeRef(relatedFontDescriptor)) {
   892     if (info == NULL) {
   893         fFontType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
   894     } else if (info->fMultiMaster) {
   895         fFontType = SkAdvancedTypefaceMetrics::kOther_Font;
   896     } else {
   897         fFontType = info->fType;
   898     }
   899 }
   901 // static
   902 SkPDFFont* SkPDFFont::Create(SkAdvancedTypefaceMetrics* info,
   903                              SkTypeface* typeface, uint16_t glyphID,
   904                              SkPDFDict* relatedFontDescriptor) {
   905     SkAdvancedTypefaceMetrics::FontType type =
   906         info ? info->fType : SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
   908     if (info && info->fMultiMaster) {
   909         NOT_IMPLEMENTED(true, true);
   910         return new SkPDFType3Font(info,
   911                                   typeface,
   912                                   glyphID);
   913     }
   914     if (type == SkAdvancedTypefaceMetrics::kType1CID_Font ||
   915         type == SkAdvancedTypefaceMetrics::kTrueType_Font) {
   916         SkASSERT(relatedFontDescriptor == NULL);
   917         return new SkPDFType0Font(info, typeface);
   918     }
   919     if (type == SkAdvancedTypefaceMetrics::kType1_Font) {
   920         return new SkPDFType1Font(info,
   921                                   typeface,
   922                                   glyphID,
   923                                   relatedFontDescriptor);
   924     }
   926     SkASSERT(type == SkAdvancedTypefaceMetrics::kCFF_Font ||
   927              type == SkAdvancedTypefaceMetrics::kOther_Font ||
   928              type == SkAdvancedTypefaceMetrics::kNotEmbeddable_Font);
   930     return new SkPDFType3Font(info, typeface, glyphID);
   931 }
   933 SkAdvancedTypefaceMetrics* SkPDFFont::fontInfo() {
   934     return fFontInfo.get();
   935 }
   937 void SkPDFFont::setFontInfo(SkAdvancedTypefaceMetrics* info) {
   938     if (info == NULL || info == fFontInfo.get()) {
   939         return;
   940     }
   941     fFontInfo.reset(info);
   942     SkSafeRef(info);
   943 }
   945 uint16_t SkPDFFont::firstGlyphID() const {
   946     return fFirstGlyphID;
   947 }
   949 uint16_t SkPDFFont::lastGlyphID() const {
   950     return fLastGlyphID;
   951 }
   953 void SkPDFFont::setLastGlyphID(uint16_t glyphID) {
   954     fLastGlyphID = glyphID;
   955 }
   957 void SkPDFFont::addResource(SkPDFObject* object) {
   958     SkASSERT(object != NULL);
   959     fResources.push(object);
   960     object->ref();
   961 }
   963 SkPDFDict* SkPDFFont::getFontDescriptor() {
   964     return fDescriptor.get();
   965 }
   967 void SkPDFFont::setFontDescriptor(SkPDFDict* descriptor) {
   968     fDescriptor.reset(descriptor);
   969     SkSafeRef(descriptor);
   970 }
   972 bool SkPDFFont::addCommonFontDescriptorEntries(int16_t defaultWidth) {
   973     if (fDescriptor.get() == NULL) {
   974         return false;
   975     }
   977     const uint16_t emSize = fFontInfo->fEmSize;
   979     fDescriptor->insertName("FontName", fFontInfo->fFontName);
   980     fDescriptor->insertInt("Flags", fFontInfo->fStyle | kPdfSymbolic);
   981     fDescriptor->insertScalar("Ascent",
   982             scaleFromFontUnits(fFontInfo->fAscent, emSize));
   983     fDescriptor->insertScalar("Descent",
   984             scaleFromFontUnits(fFontInfo->fDescent, emSize));
   985     fDescriptor->insertScalar("StemV",
   986             scaleFromFontUnits(fFontInfo->fStemV, emSize));
   987     fDescriptor->insertScalar("CapHeight",
   988             scaleFromFontUnits(fFontInfo->fCapHeight, emSize));
   989     fDescriptor->insertInt("ItalicAngle", fFontInfo->fItalicAngle);
   990     fDescriptor->insert("FontBBox", makeFontBBox(fFontInfo->fBBox,
   991                                                  fFontInfo->fEmSize))->unref();
   993     if (defaultWidth > 0) {
   994         fDescriptor->insertScalar("MissingWidth",
   995                 scaleFromFontUnits(defaultWidth, emSize));
   996     }
   997     return true;
   998 }
  1000 void SkPDFFont::adjustGlyphRangeForSingleByteEncoding(int16_t glyphID) {
  1001     // Single byte glyph encoding supports a max of 255 glyphs.
  1002     fFirstGlyphID = glyphID - (glyphID - 1) % 255;
  1003     if (fLastGlyphID > fFirstGlyphID + 255 - 1) {
  1004         fLastGlyphID = fFirstGlyphID + 255 - 1;
  1008 bool SkPDFFont::FontRec::operator==(const SkPDFFont::FontRec& b) const {
  1009     if (fFontID != b.fFontID) {
  1010         return false;
  1012     if (fFont != NULL && b.fFont != NULL) {
  1013         return fFont->fFirstGlyphID == b.fFont->fFirstGlyphID &&
  1014             fFont->fLastGlyphID == b.fFont->fLastGlyphID;
  1016     if (fGlyphID == 0 || b.fGlyphID == 0) {
  1017         return true;
  1020     if (fFont != NULL) {
  1021         return fFont->fFirstGlyphID <= b.fGlyphID &&
  1022             b.fGlyphID <= fFont->fLastGlyphID;
  1023     } else if (b.fFont != NULL) {
  1024         return b.fFont->fFirstGlyphID <= fGlyphID &&
  1025             fGlyphID <= b.fFont->fLastGlyphID;
  1027     return fGlyphID == b.fGlyphID;
  1030 SkPDFFont::FontRec::FontRec(SkPDFFont* font, uint32_t fontID, uint16_t glyphID)
  1031     : fFont(font),
  1032       fFontID(fontID),
  1033       fGlyphID(glyphID) {
  1036 void SkPDFFont::populateToUnicodeTable(const SkPDFGlyphSet* subset) {
  1037     if (fFontInfo == NULL || fFontInfo->fGlyphToUnicode.begin() == NULL) {
  1038         return;
  1040     SkAutoTUnref<SkPDFStream> pdfCmap(
  1041         generate_tounicode_cmap(fFontInfo->fGlyphToUnicode, subset,
  1042                                 multiByteGlyphs(), firstGlyphID(),
  1043                                 lastGlyphID()));
  1044     addResource(pdfCmap.get());
  1045     insert("ToUnicode", new SkPDFObjRef(pdfCmap.get()))->unref();
  1048 ///////////////////////////////////////////////////////////////////////////////
  1049 // class SkPDFType0Font
  1050 ///////////////////////////////////////////////////////////////////////////////
  1052 SkPDFType0Font::SkPDFType0Font(SkAdvancedTypefaceMetrics* info,
  1053                                SkTypeface* typeface)
  1054         : SkPDFFont(info, typeface, NULL) {
  1055     SkDEBUGCODE(fPopulated = false);
  1058 SkPDFType0Font::~SkPDFType0Font() {}
  1060 SkPDFFont* SkPDFType0Font::getFontSubset(const SkPDFGlyphSet* subset) {
  1061     SkPDFType0Font* newSubset = new SkPDFType0Font(fontInfo(), typeface());
  1062     newSubset->populate(subset);
  1063     return newSubset;
  1066 #ifdef SK_DEBUG
  1067 void SkPDFType0Font::emitObject(SkWStream* stream, SkPDFCatalog* catalog,
  1068                                 bool indirect) {
  1069     SkASSERT(fPopulated);
  1070     return INHERITED::emitObject(stream, catalog, indirect);
  1072 #endif
  1074 bool SkPDFType0Font::populate(const SkPDFGlyphSet* subset) {
  1075     insertName("Subtype", "Type0");
  1076     insertName("BaseFont", fontInfo()->fFontName);
  1077     insertName("Encoding", "Identity-H");
  1079     SkAutoTUnref<SkPDFCIDFont> newCIDFont(
  1080             new SkPDFCIDFont(fontInfo(), typeface(), subset));
  1081     addResource(newCIDFont.get());
  1082     SkAutoTUnref<SkPDFArray> descendantFonts(new SkPDFArray());
  1083     descendantFonts->append(new SkPDFObjRef(newCIDFont.get()))->unref();
  1084     insert("DescendantFonts", descendantFonts.get());
  1086     populateToUnicodeTable(subset);
  1088     SkDEBUGCODE(fPopulated = true);
  1089     return true;
  1092 ///////////////////////////////////////////////////////////////////////////////
  1093 // class SkPDFCIDFont
  1094 ///////////////////////////////////////////////////////////////////////////////
  1096 SkPDFCIDFont::SkPDFCIDFont(SkAdvancedTypefaceMetrics* info,
  1097                            SkTypeface* typeface, const SkPDFGlyphSet* subset)
  1098         : SkPDFFont(info, typeface, NULL) {
  1099     populate(subset);
  1102 SkPDFCIDFont::~SkPDFCIDFont() {}
  1104 bool SkPDFCIDFont::addFontDescriptor(int16_t defaultWidth,
  1105                                      const SkTDArray<uint32_t>* subset) {
  1106     SkAutoTUnref<SkPDFDict> descriptor(new SkPDFDict("FontDescriptor"));
  1107     setFontDescriptor(descriptor.get());
  1108     addResource(descriptor.get());
  1110     switch (getType()) {
  1111         case SkAdvancedTypefaceMetrics::kTrueType_Font: {
  1112             SkASSERT(subset);
  1113             // Font subsetting
  1114             SkPDFStream* rawStream = NULL;
  1115             int fontSize = get_subset_font_stream(fontInfo()->fFontName.c_str(),
  1116                                                   typeface(),
  1117                                                   *subset,
  1118                                                   &rawStream);
  1119             SkASSERT(fontSize);
  1120             SkASSERT(rawStream);
  1121             SkAutoTUnref<SkPDFStream> fontStream(rawStream);
  1122             addResource(fontStream.get());
  1124             fontStream->insertInt("Length1", fontSize);
  1125             descriptor->insert("FontFile2",
  1126                                new SkPDFObjRef(fontStream.get()))->unref();
  1127             break;
  1129         case SkAdvancedTypefaceMetrics::kCFF_Font:
  1130         case SkAdvancedTypefaceMetrics::kType1CID_Font: {
  1131             int ttcIndex;
  1132             SkAutoTUnref<SkStream> fontData(typeface()->openStream(&ttcIndex));
  1133             SkAutoTUnref<SkPDFStream> fontStream(
  1134                 new SkPDFStream(fontData.get()));
  1135             addResource(fontStream.get());
  1137             if (getType() == SkAdvancedTypefaceMetrics::kCFF_Font) {
  1138                 fontStream->insertName("Subtype", "Type1C");
  1139             } else {
  1140                 fontStream->insertName("Subtype", "CIDFontType0c");
  1142             descriptor->insert("FontFile3",
  1143                                 new SkPDFObjRef(fontStream.get()))->unref();
  1144             break;
  1146         default:
  1147             SkASSERT(false);
  1150     insert("FontDescriptor", new SkPDFObjRef(descriptor.get()))->unref();
  1151     return addCommonFontDescriptorEntries(defaultWidth);
  1154 bool SkPDFCIDFont::populate(const SkPDFGlyphSet* subset) {
  1155     // Generate new font metrics with advance info for true type fonts.
  1156     if (fontInfo()->fType == SkAdvancedTypefaceMetrics::kTrueType_Font) {
  1157         // Generate glyph id array.
  1158         SkTDArray<uint32_t> glyphIDs;
  1159         if (subset) {
  1160             // Always include glyph 0.
  1161             if (!subset->has(0)) {
  1162                 glyphIDs.push(0);
  1164             subset->exportTo(&glyphIDs);
  1167         SkAdvancedTypefaceMetrics::PerGlyphInfo info;
  1168         info = SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo;
  1169         info = SkTBitOr<SkAdvancedTypefaceMetrics::PerGlyphInfo>(
  1170                   info, SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo);
  1171         uint32_t* glyphs = (glyphIDs.count() == 0) ? NULL : glyphIDs.begin();
  1172         uint32_t glyphsCount = glyphs ? glyphIDs.count() : 0;
  1173         SkAutoTUnref<SkAdvancedTypefaceMetrics> fontMetrics(
  1174             typeface()->getAdvancedTypefaceMetrics(info, glyphs, glyphsCount));
  1175         setFontInfo(fontMetrics.get());
  1176         addFontDescriptor(0, &glyphIDs);
  1177     } else {
  1178         // Other CID fonts
  1179         addFontDescriptor(0, NULL);
  1182     insertName("BaseFont", fontInfo()->fFontName);
  1184     if (getType() == SkAdvancedTypefaceMetrics::kType1CID_Font) {
  1185         insertName("Subtype", "CIDFontType0");
  1186     } else if (getType() == SkAdvancedTypefaceMetrics::kTrueType_Font) {
  1187         insertName("Subtype", "CIDFontType2");
  1188         insertName("CIDToGIDMap", "Identity");
  1189     } else {
  1190         SkASSERT(false);
  1193     SkAutoTUnref<SkPDFDict> sysInfo(new SkPDFDict);
  1194     sysInfo->insert("Registry", new SkPDFString("Adobe"))->unref();
  1195     sysInfo->insert("Ordering", new SkPDFString("Identity"))->unref();
  1196     sysInfo->insertInt("Supplement", 0);
  1197     insert("CIDSystemInfo", sysInfo.get());
  1199     if (fontInfo()->fGlyphWidths.get()) {
  1200         int16_t defaultWidth = 0;
  1201         SkAutoTUnref<SkPDFArray> widths(
  1202             composeAdvanceData(fontInfo()->fGlyphWidths.get(),
  1203                                fontInfo()->fEmSize, &appendWidth,
  1204                                &defaultWidth));
  1205         if (widths->size())
  1206             insert("W", widths.get());
  1207         if (defaultWidth != 0) {
  1208             insertScalar("DW", scaleFromFontUnits(defaultWidth,
  1209                                                   fontInfo()->fEmSize));
  1212     if (fontInfo()->fVerticalMetrics.get()) {
  1213         struct SkAdvancedTypefaceMetrics::VerticalMetric defaultAdvance;
  1214         defaultAdvance.fVerticalAdvance = 0;
  1215         defaultAdvance.fOriginXDisp = 0;
  1216         defaultAdvance.fOriginYDisp = 0;
  1217         SkAutoTUnref<SkPDFArray> advances(
  1218             composeAdvanceData(fontInfo()->fVerticalMetrics.get(),
  1219                                fontInfo()->fEmSize, &appendVerticalAdvance,
  1220                                &defaultAdvance));
  1221         if (advances->size())
  1222             insert("W2", advances.get());
  1223         if (defaultAdvance.fVerticalAdvance ||
  1224                 defaultAdvance.fOriginXDisp ||
  1225                 defaultAdvance.fOriginYDisp) {
  1226             insert("DW2", appendVerticalAdvance(defaultAdvance,
  1227                                                 fontInfo()->fEmSize,
  1228                                                 new SkPDFArray))->unref();
  1232     return true;
  1235 ///////////////////////////////////////////////////////////////////////////////
  1236 // class SkPDFType1Font
  1237 ///////////////////////////////////////////////////////////////////////////////
  1239 SkPDFType1Font::SkPDFType1Font(SkAdvancedTypefaceMetrics* info,
  1240                                SkTypeface* typeface,
  1241                                uint16_t glyphID,
  1242                                SkPDFDict* relatedFontDescriptor)
  1243         : SkPDFFont(info, typeface, relatedFontDescriptor) {
  1244     populate(glyphID);
  1247 SkPDFType1Font::~SkPDFType1Font() {}
  1249 bool SkPDFType1Font::addFontDescriptor(int16_t defaultWidth) {
  1250     if (getFontDescriptor() != NULL) {
  1251         SkPDFDict* descriptor = getFontDescriptor();
  1252         addResource(descriptor);
  1253         insert("FontDescriptor", new SkPDFObjRef(descriptor))->unref();
  1254         return true;
  1257     SkAutoTUnref<SkPDFDict> descriptor(new SkPDFDict("FontDescriptor"));
  1258     setFontDescriptor(descriptor.get());
  1260     int ttcIndex;
  1261     size_t header SK_INIT_TO_AVOID_WARNING;
  1262     size_t data SK_INIT_TO_AVOID_WARNING;
  1263     size_t trailer SK_INIT_TO_AVOID_WARNING;
  1264     SkAutoTUnref<SkStream> rawFontData(typeface()->openStream(&ttcIndex));
  1265     SkStream* fontData = handleType1Stream(rawFontData.get(), &header, &data,
  1266                                            &trailer);
  1267     if (fontData == NULL) {
  1268         return false;
  1270     SkAutoTUnref<SkPDFStream> fontStream(new SkPDFStream(fontData));
  1271     addResource(fontStream.get());
  1272     fontStream->insertInt("Length1", header);
  1273     fontStream->insertInt("Length2", data);
  1274     fontStream->insertInt("Length3", trailer);
  1275     descriptor->insert("FontFile", new SkPDFObjRef(fontStream.get()))->unref();
  1277     addResource(descriptor.get());
  1278     insert("FontDescriptor", new SkPDFObjRef(descriptor.get()))->unref();
  1280     return addCommonFontDescriptorEntries(defaultWidth);
  1283 bool SkPDFType1Font::populate(int16_t glyphID) {
  1284     SkASSERT(!fontInfo()->fVerticalMetrics.get());
  1285     SkASSERT(fontInfo()->fGlyphWidths.get());
  1287     adjustGlyphRangeForSingleByteEncoding(glyphID);
  1289     int16_t defaultWidth = 0;
  1290     const SkAdvancedTypefaceMetrics::WidthRange* widthRangeEntry = NULL;
  1291     const SkAdvancedTypefaceMetrics::WidthRange* widthEntry;
  1292     for (widthEntry = fontInfo()->fGlyphWidths.get();
  1293             widthEntry != NULL;
  1294             widthEntry = widthEntry->fNext.get()) {
  1295         switch (widthEntry->fType) {
  1296             case SkAdvancedTypefaceMetrics::WidthRange::kDefault:
  1297                 defaultWidth = widthEntry->fAdvance[0];
  1298                 break;
  1299             case SkAdvancedTypefaceMetrics::WidthRange::kRun:
  1300                 SkASSERT(false);
  1301                 break;
  1302             case SkAdvancedTypefaceMetrics::WidthRange::kRange:
  1303                 SkASSERT(widthRangeEntry == NULL);
  1304                 widthRangeEntry = widthEntry;
  1305                 break;
  1309     if (!addFontDescriptor(defaultWidth)) {
  1310         return false;
  1313     insertName("Subtype", "Type1");
  1314     insertName("BaseFont", fontInfo()->fFontName);
  1316     addWidthInfoFromRange(defaultWidth, widthRangeEntry);
  1318     SkAutoTUnref<SkPDFDict> encoding(new SkPDFDict("Encoding"));
  1319     insert("Encoding", encoding.get());
  1321     SkAutoTUnref<SkPDFArray> encDiffs(new SkPDFArray);
  1322     encoding->insert("Differences", encDiffs.get());
  1324     encDiffs->reserve(lastGlyphID() - firstGlyphID() + 2);
  1325     encDiffs->appendInt(1);
  1326     for (int gID = firstGlyphID(); gID <= lastGlyphID(); gID++) {
  1327         encDiffs->appendName(fontInfo()->fGlyphNames->get()[gID].c_str());
  1330     return true;
  1333 void SkPDFType1Font::addWidthInfoFromRange(
  1334         int16_t defaultWidth,
  1335         const SkAdvancedTypefaceMetrics::WidthRange* widthRangeEntry) {
  1336     SkAutoTUnref<SkPDFArray> widthArray(new SkPDFArray());
  1337     int firstChar = 0;
  1338     if (widthRangeEntry) {
  1339         const uint16_t emSize = fontInfo()->fEmSize;
  1340         int startIndex = firstGlyphID() - widthRangeEntry->fStartId;
  1341         int endIndex = startIndex + lastGlyphID() - firstGlyphID() + 1;
  1342         if (startIndex < 0)
  1343             startIndex = 0;
  1344         if (endIndex > widthRangeEntry->fAdvance.count())
  1345             endIndex = widthRangeEntry->fAdvance.count();
  1346         if (widthRangeEntry->fStartId == 0) {
  1347             appendWidth(widthRangeEntry->fAdvance[0], emSize, widthArray.get());
  1348         } else {
  1349             firstChar = startIndex + widthRangeEntry->fStartId;
  1351         for (int i = startIndex; i < endIndex; i++) {
  1352             appendWidth(widthRangeEntry->fAdvance[i], emSize, widthArray.get());
  1354     } else {
  1355         appendWidth(defaultWidth, 1000, widthArray.get());
  1357     insertInt("FirstChar", firstChar);
  1358     insertInt("LastChar", firstChar + widthArray->size() - 1);
  1359     insert("Widths", widthArray.get());
  1362 ///////////////////////////////////////////////////////////////////////////////
  1363 // class SkPDFType3Font
  1364 ///////////////////////////////////////////////////////////////////////////////
  1366 SkPDFType3Font::SkPDFType3Font(SkAdvancedTypefaceMetrics* info,
  1367                                SkTypeface* typeface,
  1368                                uint16_t glyphID)
  1369         : SkPDFFont(info, typeface, NULL) {
  1370     populate(glyphID);
  1373 SkPDFType3Font::~SkPDFType3Font() {}
  1375 bool SkPDFType3Font::populate(int16_t glyphID) {
  1376     SkPaint paint;
  1377     paint.setTypeface(typeface());
  1378     paint.setTextSize(1000);
  1379     SkAutoGlyphCache autoCache(paint, NULL, NULL);
  1380     SkGlyphCache* cache = autoCache.getCache();
  1381     // If fLastGlyphID isn't set (because there is not fFontInfo), look it up.
  1382     if (lastGlyphID() == 0) {
  1383         setLastGlyphID(cache->getGlyphCount() - 1);
  1386     adjustGlyphRangeForSingleByteEncoding(glyphID);
  1388     insertName("Subtype", "Type3");
  1389     // Flip about the x-axis and scale by 1/1000.
  1390     SkMatrix fontMatrix;
  1391     fontMatrix.setScale(SkScalarInvert(1000), -SkScalarInvert(1000));
  1392     insert("FontMatrix", SkPDFUtils::MatrixToArray(fontMatrix))->unref();
  1394     SkAutoTUnref<SkPDFDict> charProcs(new SkPDFDict);
  1395     insert("CharProcs", charProcs.get());
  1397     SkAutoTUnref<SkPDFDict> encoding(new SkPDFDict("Encoding"));
  1398     insert("Encoding", encoding.get());
  1400     SkAutoTUnref<SkPDFArray> encDiffs(new SkPDFArray);
  1401     encoding->insert("Differences", encDiffs.get());
  1402     encDiffs->reserve(lastGlyphID() - firstGlyphID() + 2);
  1403     encDiffs->appendInt(1);
  1405     SkAutoTUnref<SkPDFArray> widthArray(new SkPDFArray());
  1407     SkIRect bbox = SkIRect::MakeEmpty();
  1408     for (int gID = firstGlyphID(); gID <= lastGlyphID(); gID++) {
  1409         SkString characterName;
  1410         characterName.printf("gid%d", gID);
  1411         encDiffs->appendName(characterName.c_str());
  1413         const SkGlyph& glyph = cache->getGlyphIDMetrics(gID);
  1414         widthArray->appendScalar(SkFixedToScalar(glyph.fAdvanceX));
  1415         SkIRect glyphBBox = SkIRect::MakeXYWH(glyph.fLeft, glyph.fTop,
  1416                                               glyph.fWidth, glyph.fHeight);
  1417         bbox.join(glyphBBox);
  1419         SkDynamicMemoryWStream content;
  1420         setGlyphWidthAndBoundingBox(SkFixedToScalar(glyph.fAdvanceX), glyphBBox,
  1421                                     &content);
  1422         const SkPath* path = cache->findPath(glyph);
  1423         if (path) {
  1424             SkPDFUtils::EmitPath(*path, paint.getStyle(), &content);
  1425             SkPDFUtils::PaintPath(paint.getStyle(), path->getFillType(),
  1426                                   &content);
  1428         SkAutoTUnref<SkMemoryStream> glyphStream(new SkMemoryStream());
  1429         glyphStream->setData(content.copyToData())->unref();
  1431         SkAutoTUnref<SkPDFStream> glyphDescription(
  1432             new SkPDFStream(glyphStream.get()));
  1433         addResource(glyphDescription.get());
  1434         charProcs->insert(characterName.c_str(),
  1435                           new SkPDFObjRef(glyphDescription.get()))->unref();
  1438     insert("FontBBox", makeFontBBox(bbox, 1000))->unref();
  1439     insertInt("FirstChar", 1);
  1440     insertInt("LastChar", lastGlyphID() - firstGlyphID() + 1);
  1441     insert("Widths", widthArray.get());
  1442     insertName("CIDToGIDMap", "Identity");
  1444     populateToUnicodeTable(NULL);
  1445     return true;

mercurial