michael@0: /* michael@0: * Copyright 2011 Google Inc. michael@0: * michael@0: * Use of this source code is governed by a BSD-style license that can be michael@0: * found in the LICENSE file. michael@0: */ michael@0: michael@0: #include michael@0: michael@0: #include "SkData.h" michael@0: #include "SkFontHost.h" michael@0: #include "SkGlyphCache.h" michael@0: #include "SkPaint.h" michael@0: #include "SkPDFCatalog.h" michael@0: #include "SkPDFDevice.h" michael@0: #include "SkPDFFont.h" michael@0: #include "SkPDFFontImpl.h" michael@0: #include "SkPDFStream.h" michael@0: #include "SkPDFTypes.h" michael@0: #include "SkPDFUtils.h" michael@0: #include "SkRefCnt.h" michael@0: #include "SkScalar.h" michael@0: #include "SkStream.h" michael@0: #include "SkTypefacePriv.h" michael@0: #include "SkTypes.h" michael@0: #include "SkUtils.h" michael@0: michael@0: #if defined (SK_SFNTLY_SUBSETTER) michael@0: #include SK_SFNTLY_SUBSETTER michael@0: #endif michael@0: michael@0: // PDF's notion of symbolic vs non-symbolic is related to the character set, not michael@0: // symbols vs. characters. Rarely is a font the right character set to call it michael@0: // non-symbolic, so always call it symbolic. (PDF 1.4 spec, section 5.7.1) michael@0: static const int kPdfSymbolic = 4; michael@0: michael@0: namespace { michael@0: michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: // File-Local Functions michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: bool parsePFBSection(const uint8_t** src, size_t* len, int sectionType, michael@0: size_t* size) { michael@0: // PFB sections have a two or six bytes header. 0x80 and a one byte michael@0: // section type followed by a four byte section length. Type one is michael@0: // an ASCII section (includes a length), type two is a binary section michael@0: // (includes a length) and type three is an EOF marker with no length. michael@0: const uint8_t* buf = *src; michael@0: if (*len < 2 || buf[0] != 0x80 || buf[1] != sectionType) { michael@0: return false; michael@0: } else if (buf[1] == 3) { michael@0: return true; michael@0: } else if (*len < 6) { michael@0: return false; michael@0: } michael@0: michael@0: *size = (size_t)buf[2] | ((size_t)buf[3] << 8) | ((size_t)buf[4] << 16) | michael@0: ((size_t)buf[5] << 24); michael@0: size_t consumed = *size + 6; michael@0: if (consumed > *len) { michael@0: return false; michael@0: } michael@0: *src = *src + consumed; michael@0: *len = *len - consumed; michael@0: return true; michael@0: } michael@0: michael@0: bool parsePFB(const uint8_t* src, size_t size, size_t* headerLen, michael@0: size_t* dataLen, size_t* trailerLen) { michael@0: const uint8_t* srcPtr = src; michael@0: size_t remaining = size; michael@0: michael@0: return parsePFBSection(&srcPtr, &remaining, 1, headerLen) && michael@0: parsePFBSection(&srcPtr, &remaining, 2, dataLen) && michael@0: parsePFBSection(&srcPtr, &remaining, 1, trailerLen) && michael@0: parsePFBSection(&srcPtr, &remaining, 3, NULL); michael@0: } michael@0: michael@0: /* The sections of a PFA file are implicitly defined. The body starts michael@0: * after the line containing "eexec," and the trailer starts with 512 michael@0: * literal 0's followed by "cleartomark" (plus arbitrary white space). michael@0: * michael@0: * This function assumes that src is NUL terminated, but the NUL michael@0: * termination is not included in size. michael@0: * michael@0: */ michael@0: bool parsePFA(const char* src, size_t size, size_t* headerLen, michael@0: size_t* hexDataLen, size_t* dataLen, size_t* trailerLen) { michael@0: const char* end = src + size; michael@0: michael@0: const char* dataPos = strstr(src, "eexec"); michael@0: if (!dataPos) { michael@0: return false; michael@0: } michael@0: dataPos += strlen("eexec"); michael@0: while ((*dataPos == '\n' || *dataPos == '\r' || *dataPos == ' ') && michael@0: dataPos < end) { michael@0: dataPos++; michael@0: } michael@0: *headerLen = dataPos - src; michael@0: michael@0: const char* trailerPos = strstr(dataPos, "cleartomark"); michael@0: if (!trailerPos) { michael@0: return false; michael@0: } michael@0: int zeroCount = 0; michael@0: for (trailerPos--; trailerPos > dataPos && zeroCount < 512; trailerPos--) { michael@0: if (*trailerPos == '\n' || *trailerPos == '\r' || *trailerPos == ' ') { michael@0: continue; michael@0: } else if (*trailerPos == '0') { michael@0: zeroCount++; michael@0: } else { michael@0: return false; michael@0: } michael@0: } michael@0: if (zeroCount != 512) { michael@0: return false; michael@0: } michael@0: michael@0: *hexDataLen = trailerPos - src - *headerLen; michael@0: *trailerLen = size - *headerLen - *hexDataLen; michael@0: michael@0: // Verify that the data section is hex encoded and count the bytes. michael@0: int nibbles = 0; michael@0: for (; dataPos < trailerPos; dataPos++) { michael@0: if (isspace(*dataPos)) { michael@0: continue; michael@0: } michael@0: if (!isxdigit(*dataPos)) { michael@0: return false; michael@0: } michael@0: nibbles++; michael@0: } michael@0: *dataLen = (nibbles + 1) / 2; michael@0: michael@0: return true; michael@0: } michael@0: michael@0: int8_t hexToBin(uint8_t c) { michael@0: if (!isxdigit(c)) { michael@0: return -1; michael@0: } else if (c <= '9') { michael@0: return c - '0'; michael@0: } else if (c <= 'F') { michael@0: return c - 'A' + 10; michael@0: } else if (c <= 'f') { michael@0: return c - 'a' + 10; michael@0: } michael@0: return -1; michael@0: } michael@0: michael@0: SkStream* handleType1Stream(SkStream* srcStream, size_t* headerLen, michael@0: size_t* dataLen, size_t* trailerLen) { michael@0: // srcStream may be backed by a file or a unseekable fd, so we may not be michael@0: // able to use skip(), rewind(), or getMemoryBase(). read()ing through michael@0: // the input only once is doable, but very ugly. Furthermore, it'd be nice michael@0: // if the data was NUL terminated so that we can use strstr() to search it. michael@0: // Make as few copies as possible given these constraints. michael@0: SkDynamicMemoryWStream dynamicStream; michael@0: SkAutoTUnref staticStream; michael@0: SkData* data = NULL; michael@0: const uint8_t* src; michael@0: size_t srcLen; michael@0: if ((srcLen = srcStream->getLength()) > 0) { michael@0: staticStream.reset(new SkMemoryStream(srcLen + 1)); michael@0: src = (const uint8_t*)staticStream->getMemoryBase(); michael@0: if (srcStream->getMemoryBase() != NULL) { michael@0: memcpy((void *)src, srcStream->getMemoryBase(), srcLen); michael@0: } else { michael@0: size_t read = 0; michael@0: while (read < srcLen) { michael@0: size_t got = srcStream->read((void *)staticStream->getAtPos(), michael@0: srcLen - read); michael@0: if (got == 0) { michael@0: return NULL; michael@0: } michael@0: read += got; michael@0: staticStream->seek(read); michael@0: } michael@0: } michael@0: ((uint8_t *)src)[srcLen] = 0; michael@0: } else { michael@0: static const size_t kBufSize = 4096; michael@0: uint8_t buf[kBufSize]; michael@0: size_t amount; michael@0: while ((amount = srcStream->read(buf, kBufSize)) > 0) { michael@0: dynamicStream.write(buf, amount); michael@0: } michael@0: amount = 0; michael@0: dynamicStream.write(&amount, 1); // NULL terminator. michael@0: data = dynamicStream.copyToData(); michael@0: src = data->bytes(); michael@0: srcLen = data->size() - 1; michael@0: } michael@0: michael@0: // this handles releasing the data we may have gotten from dynamicStream. michael@0: // if data is null, it is a no-op michael@0: SkAutoDataUnref aud(data); michael@0: michael@0: if (parsePFB(src, srcLen, headerLen, dataLen, trailerLen)) { michael@0: SkMemoryStream* result = michael@0: new SkMemoryStream(*headerLen + *dataLen + *trailerLen); michael@0: memcpy((char*)result->getAtPos(), src + 6, *headerLen); michael@0: result->seek(*headerLen); michael@0: memcpy((char*)result->getAtPos(), src + 6 + *headerLen + 6, *dataLen); michael@0: result->seek(*headerLen + *dataLen); michael@0: memcpy((char*)result->getAtPos(), src + 6 + *headerLen + 6 + *dataLen, michael@0: *trailerLen); michael@0: result->rewind(); michael@0: return result; michael@0: } michael@0: michael@0: // A PFA has to be converted for PDF. michael@0: size_t hexDataLen; michael@0: if (parsePFA((const char*)src, srcLen, headerLen, &hexDataLen, dataLen, michael@0: trailerLen)) { michael@0: SkMemoryStream* result = michael@0: new SkMemoryStream(*headerLen + *dataLen + *trailerLen); michael@0: memcpy((char*)result->getAtPos(), src, *headerLen); michael@0: result->seek(*headerLen); michael@0: michael@0: const uint8_t* hexData = src + *headerLen; michael@0: const uint8_t* trailer = hexData + hexDataLen; michael@0: size_t outputOffset = 0; michael@0: uint8_t dataByte = 0; // To hush compiler. michael@0: bool highNibble = true; michael@0: for (; hexData < trailer; hexData++) { michael@0: int8_t curNibble = hexToBin(*hexData); michael@0: if (curNibble < 0) { michael@0: continue; michael@0: } michael@0: if (highNibble) { michael@0: dataByte = curNibble << 4; michael@0: highNibble = false; michael@0: } else { michael@0: dataByte |= curNibble; michael@0: highNibble = true; michael@0: ((char *)result->getAtPos())[outputOffset++] = dataByte; michael@0: } michael@0: } michael@0: if (!highNibble) { michael@0: ((char *)result->getAtPos())[outputOffset++] = dataByte; michael@0: } michael@0: SkASSERT(outputOffset == *dataLen); michael@0: result->seek(*headerLen + outputOffset); michael@0: michael@0: memcpy((char *)result->getAtPos(), src + *headerLen + hexDataLen, michael@0: *trailerLen); michael@0: result->rewind(); michael@0: return result; michael@0: } michael@0: michael@0: return NULL; michael@0: } michael@0: michael@0: // scale from em-units to base-1000, returning as a SkScalar michael@0: SkScalar scaleFromFontUnits(int16_t val, uint16_t emSize) { michael@0: SkScalar scaled = SkIntToScalar(val); michael@0: if (emSize == 1000) { michael@0: return scaled; michael@0: } else { michael@0: return SkScalarMulDiv(scaled, 1000, emSize); michael@0: } michael@0: } michael@0: michael@0: void setGlyphWidthAndBoundingBox(SkScalar width, SkIRect box, michael@0: SkWStream* content) { michael@0: // Specify width and bounding box for the glyph. michael@0: SkPDFScalar::Append(width, content); michael@0: content->writeText(" 0 "); michael@0: content->writeDecAsText(box.fLeft); michael@0: content->writeText(" "); michael@0: content->writeDecAsText(box.fTop); michael@0: content->writeText(" "); michael@0: content->writeDecAsText(box.fRight); michael@0: content->writeText(" "); michael@0: content->writeDecAsText(box.fBottom); michael@0: content->writeText(" d1\n"); michael@0: } michael@0: michael@0: SkPDFArray* makeFontBBox(SkIRect glyphBBox, uint16_t emSize) { michael@0: SkPDFArray* bbox = new SkPDFArray; michael@0: bbox->reserve(4); michael@0: bbox->appendScalar(scaleFromFontUnits(glyphBBox.fLeft, emSize)); michael@0: bbox->appendScalar(scaleFromFontUnits(glyphBBox.fBottom, emSize)); michael@0: bbox->appendScalar(scaleFromFontUnits(glyphBBox.fRight, emSize)); michael@0: bbox->appendScalar(scaleFromFontUnits(glyphBBox.fTop, emSize)); michael@0: return bbox; michael@0: } michael@0: michael@0: SkPDFArray* appendWidth(const int16_t& width, uint16_t emSize, michael@0: SkPDFArray* array) { michael@0: array->appendScalar(scaleFromFontUnits(width, emSize)); michael@0: return array; michael@0: } michael@0: michael@0: SkPDFArray* appendVerticalAdvance( michael@0: const SkAdvancedTypefaceMetrics::VerticalMetric& advance, michael@0: uint16_t emSize, SkPDFArray* array) { michael@0: appendWidth(advance.fVerticalAdvance, emSize, array); michael@0: appendWidth(advance.fOriginXDisp, emSize, array); michael@0: appendWidth(advance.fOriginYDisp, emSize, array); michael@0: return array; michael@0: } michael@0: michael@0: template michael@0: SkPDFArray* composeAdvanceData( michael@0: SkAdvancedTypefaceMetrics::AdvanceMetric* advanceInfo, michael@0: uint16_t emSize, michael@0: SkPDFArray* (*appendAdvance)(const Data& advance, uint16_t emSize, michael@0: SkPDFArray* array), michael@0: Data* defaultAdvance) { michael@0: SkPDFArray* result = new SkPDFArray(); michael@0: for (; advanceInfo != NULL; advanceInfo = advanceInfo->fNext.get()) { michael@0: switch (advanceInfo->fType) { michael@0: case SkAdvancedTypefaceMetrics::WidthRange::kDefault: { michael@0: SkASSERT(advanceInfo->fAdvance.count() == 1); michael@0: *defaultAdvance = advanceInfo->fAdvance[0]; michael@0: break; michael@0: } michael@0: case SkAdvancedTypefaceMetrics::WidthRange::kRange: { michael@0: SkAutoTUnref advanceArray(new SkPDFArray()); michael@0: for (int j = 0; j < advanceInfo->fAdvance.count(); j++) michael@0: appendAdvance(advanceInfo->fAdvance[j], emSize, michael@0: advanceArray.get()); michael@0: result->appendInt(advanceInfo->fStartId); michael@0: result->append(advanceArray.get()); michael@0: break; michael@0: } michael@0: case SkAdvancedTypefaceMetrics::WidthRange::kRun: { michael@0: SkASSERT(advanceInfo->fAdvance.count() == 1); michael@0: result->appendInt(advanceInfo->fStartId); michael@0: result->appendInt(advanceInfo->fEndId); michael@0: appendAdvance(advanceInfo->fAdvance[0], emSize, result); michael@0: break; michael@0: } michael@0: } michael@0: } michael@0: return result; michael@0: } michael@0: michael@0: } // namespace michael@0: michael@0: static void append_tounicode_header(SkDynamicMemoryWStream* cmap, michael@0: uint16_t firstGlyphID, michael@0: uint16_t lastGlyphID) { michael@0: // 12 dict begin: 12 is an Adobe-suggested value. Shall not change. michael@0: // It's there to prevent old version Adobe Readers from malfunctioning. michael@0: const char* kHeader = michael@0: "/CIDInit /ProcSet findresource begin\n" michael@0: "12 dict begin\n" michael@0: "begincmap\n"; michael@0: cmap->writeText(kHeader); michael@0: michael@0: // The /CIDSystemInfo must be consistent to the one in michael@0: // SkPDFFont::populateCIDFont(). michael@0: // We can not pass over the system info object here because the format is michael@0: // different. This is not a reference object. michael@0: const char* kSysInfo = michael@0: "/CIDSystemInfo\n" michael@0: "<< /Registry (Adobe)\n" michael@0: "/Ordering (UCS)\n" michael@0: "/Supplement 0\n" michael@0: ">> def\n"; michael@0: cmap->writeText(kSysInfo); michael@0: michael@0: // The CMapName must be consistent to /CIDSystemInfo above. michael@0: // /CMapType 2 means ToUnicode. michael@0: // Codespace range just tells the PDF processor the valid range. michael@0: const char* kTypeInfoHeader = michael@0: "/CMapName /Adobe-Identity-UCS def\n" michael@0: "/CMapType 2 def\n" michael@0: "1 begincodespacerange\n"; michael@0: cmap->writeText(kTypeInfoHeader); michael@0: michael@0: // e.g. "<0000> \n" michael@0: SkString range; michael@0: range.appendf("<%04X> <%04X>\n", firstGlyphID, lastGlyphID); michael@0: cmap->writeText(range.c_str()); michael@0: michael@0: const char* kTypeInfoFooter = "endcodespacerange\n"; michael@0: cmap->writeText(kTypeInfoFooter); michael@0: } michael@0: michael@0: static void append_cmap_footer(SkDynamicMemoryWStream* cmap) { michael@0: const char* kFooter = michael@0: "endcmap\n" michael@0: "CMapName currentdict /CMap defineresource pop\n" michael@0: "end\n" michael@0: "end"; michael@0: cmap->writeText(kFooter); michael@0: } michael@0: michael@0: struct BFChar { michael@0: uint16_t fGlyphId; michael@0: SkUnichar fUnicode; michael@0: }; michael@0: michael@0: struct BFRange { michael@0: uint16_t fStart; michael@0: uint16_t fEnd; michael@0: SkUnichar fUnicode; michael@0: }; michael@0: michael@0: static void append_bfchar_section(const SkTDArray& bfchar, michael@0: SkDynamicMemoryWStream* cmap) { michael@0: // PDF spec defines that every bf* list can have at most 100 entries. michael@0: for (int i = 0; i < bfchar.count(); i += 100) { michael@0: int count = bfchar.count() - i; michael@0: count = SkMin32(count, 100); michael@0: cmap->writeDecAsText(count); michael@0: cmap->writeText(" beginbfchar\n"); michael@0: for (int j = 0; j < count; ++j) { michael@0: cmap->writeText("<"); michael@0: cmap->writeHexAsText(bfchar[i + j].fGlyphId, 4); michael@0: cmap->writeText("> <"); michael@0: cmap->writeHexAsText(bfchar[i + j].fUnicode, 4); michael@0: cmap->writeText(">\n"); michael@0: } michael@0: cmap->writeText("endbfchar\n"); michael@0: } michael@0: } michael@0: michael@0: static void append_bfrange_section(const SkTDArray& bfrange, michael@0: SkDynamicMemoryWStream* cmap) { michael@0: // PDF spec defines that every bf* list can have at most 100 entries. michael@0: for (int i = 0; i < bfrange.count(); i += 100) { michael@0: int count = bfrange.count() - i; michael@0: count = SkMin32(count, 100); michael@0: cmap->writeDecAsText(count); michael@0: cmap->writeText(" beginbfrange\n"); michael@0: for (int j = 0; j < count; ++j) { michael@0: cmap->writeText("<"); michael@0: cmap->writeHexAsText(bfrange[i + j].fStart, 4); michael@0: cmap->writeText("> <"); michael@0: cmap->writeHexAsText(bfrange[i + j].fEnd, 4); michael@0: cmap->writeText("> <"); michael@0: cmap->writeHexAsText(bfrange[i + j].fUnicode, 4); michael@0: cmap->writeText(">\n"); michael@0: } michael@0: cmap->writeText("endbfrange\n"); michael@0: } michael@0: } michael@0: michael@0: // Generate and table according to PDF spec 1.4 and Adobe michael@0: // Technote 5014. michael@0: // The function is not static so we can test it in unit tests. michael@0: // michael@0: // Current implementation guarantees bfchar and bfrange entries do not overlap. michael@0: // michael@0: // Current implementation does not attempt aggresive optimizations against michael@0: // following case because the specification is not clear. michael@0: // michael@0: // 4 beginbfchar 1 beginbfchar michael@0: // <0003> <0013> <0020> <0014> michael@0: // <0005> <0015> to endbfchar michael@0: // <0007> <0017> 1 beginbfrange michael@0: // <0020> <0014> <0003> <0007> <0013> michael@0: // endbfchar endbfrange michael@0: // michael@0: // Adobe Technote 5014 said: "Code mappings (unlike codespace ranges) may michael@0: // overlap, but succeeding maps supersede preceding maps." michael@0: // michael@0: // In case of searching text in PDF, bfrange will have higher precedence so michael@0: // typing char id 0x0014 in search box will get glyph id 0x0004 first. However, michael@0: // the spec does not mention how will this kind of conflict being resolved. michael@0: // michael@0: // For the worst case (having 65536 continuous unicode and we use every other michael@0: // one of them), the possible savings by aggressive optimization is 416KB michael@0: // pre-compressed and does not provide enough motivation for implementation. michael@0: michael@0: // FIXME: this should be in a header so that it is separately testable michael@0: // ( see caller in tests/ToUnicode.cpp ) michael@0: void append_cmap_sections(const SkTDArray& glyphToUnicode, michael@0: const SkPDFGlyphSet* subset, michael@0: SkDynamicMemoryWStream* cmap, michael@0: bool multiByteGlyphs, michael@0: uint16_t firstGlyphID, michael@0: uint16_t lastGlyphID); michael@0: michael@0: void append_cmap_sections(const SkTDArray& glyphToUnicode, michael@0: const SkPDFGlyphSet* subset, michael@0: SkDynamicMemoryWStream* cmap, michael@0: bool multiByteGlyphs, michael@0: uint16_t firstGlyphID, michael@0: uint16_t lastGlyphID) { michael@0: if (glyphToUnicode.isEmpty()) { michael@0: return; michael@0: } michael@0: int glyphOffset = 0; michael@0: if (!multiByteGlyphs) { michael@0: glyphOffset = firstGlyphID - 1; michael@0: } michael@0: michael@0: SkTDArray bfcharEntries; michael@0: SkTDArray bfrangeEntries; michael@0: michael@0: BFRange currentRangeEntry = {0, 0, 0}; michael@0: bool rangeEmpty = true; michael@0: const int limit = michael@0: SkMin32(lastGlyphID + 1, glyphToUnicode.count()) - glyphOffset; michael@0: michael@0: for (int i = firstGlyphID - glyphOffset; i < limit + 1; ++i) { michael@0: bool inSubset = i < limit && michael@0: (subset == NULL || subset->has(i + glyphOffset)); michael@0: if (!rangeEmpty) { michael@0: // PDF spec requires bfrange not changing the higher byte, michael@0: // e.g. <1035> <10FF> <2222> is ok, but michael@0: // <1035> <1100> <2222> is no good michael@0: bool inRange = michael@0: i == currentRangeEntry.fEnd + 1 && michael@0: i >> 8 == currentRangeEntry.fStart >> 8 && michael@0: i < limit && michael@0: glyphToUnicode[i + glyphOffset] == michael@0: currentRangeEntry.fUnicode + i - currentRangeEntry.fStart; michael@0: if (!inSubset || !inRange) { michael@0: if (currentRangeEntry.fEnd > currentRangeEntry.fStart) { michael@0: bfrangeEntries.push(currentRangeEntry); michael@0: } else { michael@0: BFChar* entry = bfcharEntries.append(); michael@0: entry->fGlyphId = currentRangeEntry.fStart; michael@0: entry->fUnicode = currentRangeEntry.fUnicode; michael@0: } michael@0: rangeEmpty = true; michael@0: } michael@0: } michael@0: if (inSubset) { michael@0: currentRangeEntry.fEnd = i; michael@0: if (rangeEmpty) { michael@0: currentRangeEntry.fStart = i; michael@0: currentRangeEntry.fUnicode = glyphToUnicode[i + glyphOffset]; michael@0: rangeEmpty = false; michael@0: } michael@0: } michael@0: } michael@0: michael@0: // The spec requires all bfchar entries for a font must come before bfrange michael@0: // entries. michael@0: append_bfchar_section(bfcharEntries, cmap); michael@0: append_bfrange_section(bfrangeEntries, cmap); michael@0: } michael@0: michael@0: static SkPDFStream* generate_tounicode_cmap( michael@0: const SkTDArray& glyphToUnicode, michael@0: const SkPDFGlyphSet* subset, michael@0: bool multiByteGlyphs, michael@0: uint16_t firstGlyphID, michael@0: uint16_t lastGlyphID) { michael@0: SkDynamicMemoryWStream cmap; michael@0: if (multiByteGlyphs) { michael@0: append_tounicode_header(&cmap, firstGlyphID, lastGlyphID); michael@0: } else { michael@0: append_tounicode_header(&cmap, 1, lastGlyphID - firstGlyphID + 1); michael@0: } michael@0: append_cmap_sections(glyphToUnicode, subset, &cmap, multiByteGlyphs, michael@0: firstGlyphID, lastGlyphID); michael@0: append_cmap_footer(&cmap); michael@0: SkAutoTUnref cmapStream(new SkMemoryStream()); michael@0: cmapStream->setData(cmap.copyToData())->unref(); michael@0: return new SkPDFStream(cmapStream.get()); michael@0: } michael@0: michael@0: #if defined (SK_SFNTLY_SUBSETTER) michael@0: static void sk_delete_array(const void* ptr, size_t, void*) { michael@0: // Use C-style cast to cast away const and cast type simultaneously. michael@0: delete[] (unsigned char*)ptr; michael@0: } michael@0: #endif michael@0: michael@0: static int get_subset_font_stream(const char* fontName, michael@0: const SkTypeface* typeface, michael@0: const SkTDArray& subset, michael@0: SkPDFStream** fontStream) { michael@0: int ttcIndex; michael@0: SkAutoTUnref fontData(typeface->openStream(&ttcIndex)); michael@0: michael@0: int fontSize = fontData->getLength(); michael@0: michael@0: #if defined (SK_SFNTLY_SUBSETTER) michael@0: // Read font into buffer. michael@0: SkPDFStream* subsetFontStream = NULL; michael@0: SkTDArray originalFont; michael@0: originalFont.setCount(fontSize); michael@0: if (fontData->read(originalFont.begin(), fontSize) == (size_t)fontSize) { michael@0: unsigned char* subsetFont = NULL; michael@0: // sfntly requires unsigned int* to be passed in, as far as we know, michael@0: // unsigned int is equivalent to uint32_t on all platforms. michael@0: SK_COMPILE_ASSERT(sizeof(unsigned int) == sizeof(uint32_t), michael@0: unsigned_int_not_32_bits); michael@0: int subsetFontSize = SfntlyWrapper::SubsetFont(fontName, michael@0: originalFont.begin(), michael@0: fontSize, michael@0: subset.begin(), michael@0: subset.count(), michael@0: &subsetFont); michael@0: if (subsetFontSize > 0 && subsetFont != NULL) { michael@0: SkAutoDataUnref data(SkData::NewWithProc(subsetFont, michael@0: subsetFontSize, michael@0: sk_delete_array, michael@0: NULL)); michael@0: subsetFontStream = new SkPDFStream(data.get()); michael@0: fontSize = subsetFontSize; michael@0: } michael@0: } michael@0: if (subsetFontStream) { michael@0: *fontStream = subsetFontStream; michael@0: return fontSize; michael@0: } michael@0: fontData->rewind(); michael@0: #else michael@0: sk_ignore_unused_variable(fontName); michael@0: sk_ignore_unused_variable(subset); michael@0: #endif michael@0: michael@0: // Fail over: just embed the whole font. michael@0: *fontStream = new SkPDFStream(fontData.get()); michael@0: return fontSize; michael@0: } michael@0: michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: // class SkPDFGlyphSet michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: SkPDFGlyphSet::SkPDFGlyphSet() : fBitSet(SK_MaxU16 + 1) { michael@0: } michael@0: michael@0: void SkPDFGlyphSet::set(const uint16_t* glyphIDs, int numGlyphs) { michael@0: for (int i = 0; i < numGlyphs; ++i) { michael@0: fBitSet.setBit(glyphIDs[i], true); michael@0: } michael@0: } michael@0: michael@0: bool SkPDFGlyphSet::has(uint16_t glyphID) const { michael@0: return fBitSet.isBitSet(glyphID); michael@0: } michael@0: michael@0: void SkPDFGlyphSet::merge(const SkPDFGlyphSet& usage) { michael@0: fBitSet.orBits(usage.fBitSet); michael@0: } michael@0: michael@0: void SkPDFGlyphSet::exportTo(SkTDArray* glyphIDs) const { michael@0: fBitSet.exportTo(glyphIDs); michael@0: } michael@0: michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: // class SkPDFGlyphSetMap michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: SkPDFGlyphSetMap::FontGlyphSetPair::FontGlyphSetPair(SkPDFFont* font, michael@0: SkPDFGlyphSet* glyphSet) michael@0: : fFont(font), michael@0: fGlyphSet(glyphSet) { michael@0: } michael@0: michael@0: SkPDFGlyphSetMap::F2BIter::F2BIter(const SkPDFGlyphSetMap& map) { michael@0: reset(map); michael@0: } michael@0: michael@0: const SkPDFGlyphSetMap::FontGlyphSetPair* SkPDFGlyphSetMap::F2BIter::next() const { michael@0: if (fIndex >= fMap->count()) { michael@0: return NULL; michael@0: } michael@0: return &((*fMap)[fIndex++]); michael@0: } michael@0: michael@0: void SkPDFGlyphSetMap::F2BIter::reset(const SkPDFGlyphSetMap& map) { michael@0: fMap = &(map.fMap); michael@0: fIndex = 0; michael@0: } michael@0: michael@0: SkPDFGlyphSetMap::SkPDFGlyphSetMap() { michael@0: } michael@0: michael@0: SkPDFGlyphSetMap::~SkPDFGlyphSetMap() { michael@0: reset(); michael@0: } michael@0: michael@0: void SkPDFGlyphSetMap::merge(const SkPDFGlyphSetMap& usage) { michael@0: for (int i = 0; i < usage.fMap.count(); ++i) { michael@0: SkPDFGlyphSet* myUsage = getGlyphSetForFont(usage.fMap[i].fFont); michael@0: myUsage->merge(*(usage.fMap[i].fGlyphSet)); michael@0: } michael@0: } michael@0: michael@0: void SkPDFGlyphSetMap::reset() { michael@0: for (int i = 0; i < fMap.count(); ++i) { michael@0: delete fMap[i].fGlyphSet; // Should not be NULL. michael@0: } michael@0: fMap.reset(); michael@0: } michael@0: michael@0: void SkPDFGlyphSetMap::noteGlyphUsage(SkPDFFont* font, const uint16_t* glyphIDs, michael@0: int numGlyphs) { michael@0: SkPDFGlyphSet* subset = getGlyphSetForFont(font); michael@0: if (subset) { michael@0: subset->set(glyphIDs, numGlyphs); michael@0: } michael@0: } michael@0: michael@0: SkPDFGlyphSet* SkPDFGlyphSetMap::getGlyphSetForFont(SkPDFFont* font) { michael@0: int index = fMap.count(); michael@0: for (int i = 0; i < index; ++i) { michael@0: if (fMap[i].fFont == font) { michael@0: return fMap[i].fGlyphSet; michael@0: } michael@0: } michael@0: fMap.append(); michael@0: index = fMap.count() - 1; michael@0: fMap[index].fFont = font; michael@0: fMap[index].fGlyphSet = new SkPDFGlyphSet(); michael@0: return fMap[index].fGlyphSet; michael@0: } michael@0: michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: // class SkPDFFont michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: /* Font subset design: It would be nice to be able to subset fonts michael@0: * (particularly type 3 fonts), but it's a lot of work and not a priority. michael@0: * michael@0: * Resources are canonicalized and uniqueified by pointer so there has to be michael@0: * some additional state indicating which subset of the font is used. It michael@0: * must be maintained at the page granularity and then combined at the document michael@0: * granularity. a) change SkPDFFont to fill in its state on demand, kind of michael@0: * like SkPDFGraphicState. b) maintain a per font glyph usage class in each michael@0: * page/pdf device. c) in the document, retrieve the per font glyph usage michael@0: * from each page and combine it and ask for a resource with that subset. michael@0: */ michael@0: michael@0: SkPDFFont::~SkPDFFont() { michael@0: SkAutoMutexAcquire lock(CanonicalFontsMutex()); michael@0: int index = -1; michael@0: for (int i = 0 ; i < CanonicalFonts().count() ; i++) { michael@0: if (CanonicalFonts()[i].fFont == this) { michael@0: index = i; michael@0: } michael@0: } michael@0: michael@0: SkDEBUGCODE(int indexFound;) michael@0: SkASSERT(index == -1 || michael@0: (Find(fTypeface->uniqueID(), michael@0: fFirstGlyphID, michael@0: &indexFound) && michael@0: index == indexFound)); michael@0: if (index >= 0) { michael@0: CanonicalFonts().removeShuffle(index); michael@0: } michael@0: fResources.unrefAll(); michael@0: } michael@0: michael@0: void SkPDFFont::getResources(const SkTSet& knownResourceObjects, michael@0: SkTSet* newResourceObjects) { michael@0: GetResourcesHelper(&fResources, knownResourceObjects, newResourceObjects); michael@0: } michael@0: michael@0: SkTypeface* SkPDFFont::typeface() { michael@0: return fTypeface.get(); michael@0: } michael@0: michael@0: SkAdvancedTypefaceMetrics::FontType SkPDFFont::getType() { michael@0: return fFontType; michael@0: } michael@0: michael@0: bool SkPDFFont::hasGlyph(uint16_t id) { michael@0: return (id >= fFirstGlyphID && id <= fLastGlyphID) || id == 0; michael@0: } michael@0: michael@0: size_t SkPDFFont::glyphsToPDFFontEncoding(uint16_t* glyphIDs, michael@0: size_t numGlyphs) { michael@0: // A font with multibyte glyphs will support all glyph IDs in a single font. michael@0: if (this->multiByteGlyphs()) { michael@0: return numGlyphs; michael@0: } michael@0: michael@0: for (size_t i = 0; i < numGlyphs; i++) { michael@0: if (glyphIDs[i] == 0) { michael@0: continue; michael@0: } michael@0: if (glyphIDs[i] < fFirstGlyphID || glyphIDs[i] > fLastGlyphID) { michael@0: return i; michael@0: } michael@0: glyphIDs[i] -= (fFirstGlyphID - 1); michael@0: } michael@0: michael@0: return numGlyphs; michael@0: } michael@0: michael@0: // static michael@0: SkPDFFont* SkPDFFont::GetFontResource(SkTypeface* typeface, uint16_t glyphID) { michael@0: SkAutoMutexAcquire lock(CanonicalFontsMutex()); michael@0: michael@0: SkAutoResolveDefaultTypeface autoResolve(typeface); michael@0: typeface = autoResolve.get(); michael@0: michael@0: const uint32_t fontID = typeface->uniqueID(); michael@0: int relatedFontIndex; michael@0: if (Find(fontID, glyphID, &relatedFontIndex)) { michael@0: CanonicalFonts()[relatedFontIndex].fFont->ref(); michael@0: return CanonicalFonts()[relatedFontIndex].fFont; michael@0: } michael@0: michael@0: SkAutoTUnref fontMetrics; michael@0: SkPDFDict* relatedFontDescriptor = NULL; michael@0: if (relatedFontIndex >= 0) { michael@0: SkPDFFont* relatedFont = CanonicalFonts()[relatedFontIndex].fFont; michael@0: fontMetrics.reset(relatedFont->fontInfo()); michael@0: SkSafeRef(fontMetrics.get()); michael@0: relatedFontDescriptor = relatedFont->getFontDescriptor(); michael@0: michael@0: // This only is to catch callers who pass invalid glyph ids. michael@0: // If glyph id is invalid, then we will create duplicate entries michael@0: // for True Type fonts. michael@0: SkAdvancedTypefaceMetrics::FontType fontType = michael@0: fontMetrics.get() ? fontMetrics.get()->fType : michael@0: SkAdvancedTypefaceMetrics::kOther_Font; michael@0: michael@0: if (fontType == SkAdvancedTypefaceMetrics::kType1CID_Font || michael@0: fontType == SkAdvancedTypefaceMetrics::kTrueType_Font) { michael@0: CanonicalFonts()[relatedFontIndex].fFont->ref(); michael@0: return CanonicalFonts()[relatedFontIndex].fFont; michael@0: } michael@0: } else { michael@0: SkAdvancedTypefaceMetrics::PerGlyphInfo info; michael@0: info = SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo; michael@0: info = SkTBitOr( michael@0: info, SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo); michael@0: #if !defined (SK_SFNTLY_SUBSETTER) michael@0: info = SkTBitOr( michael@0: info, SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo); michael@0: #endif michael@0: fontMetrics.reset( michael@0: typeface->getAdvancedTypefaceMetrics(info, NULL, 0)); michael@0: #if defined (SK_SFNTLY_SUBSETTER) michael@0: if (fontMetrics.get() && michael@0: fontMetrics->fType != SkAdvancedTypefaceMetrics::kTrueType_Font) { michael@0: // Font does not support subsetting, get new info with advance. michael@0: info = SkTBitOr( michael@0: info, SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo); michael@0: fontMetrics.reset( michael@0: typeface->getAdvancedTypefaceMetrics(info, NULL, 0)); michael@0: } michael@0: #endif michael@0: } michael@0: michael@0: SkPDFFont* font = Create(fontMetrics.get(), typeface, glyphID, michael@0: relatedFontDescriptor); michael@0: FontRec newEntry(font, fontID, font->fFirstGlyphID); michael@0: CanonicalFonts().push(newEntry); michael@0: return font; // Return the reference new SkPDFFont() created. michael@0: } michael@0: michael@0: SkPDFFont* SkPDFFont::getFontSubset(const SkPDFGlyphSet*) { michael@0: return NULL; // Default: no support. michael@0: } michael@0: michael@0: // static michael@0: SkTDArray& SkPDFFont::CanonicalFonts() { michael@0: // This initialization is only thread safe with gcc. michael@0: static SkTDArray gCanonicalFonts; michael@0: return gCanonicalFonts; michael@0: } michael@0: michael@0: // static michael@0: SkBaseMutex& SkPDFFont::CanonicalFontsMutex() { michael@0: // This initialization is only thread safe with gcc, or when michael@0: // POD-style mutex initialization is used. michael@0: SK_DECLARE_STATIC_MUTEX(gCanonicalFontsMutex); michael@0: return gCanonicalFontsMutex; michael@0: } michael@0: michael@0: // static michael@0: bool SkPDFFont::Find(uint32_t fontID, uint16_t glyphID, int* index) { michael@0: // TODO(vandebo): Optimize this, do only one search? michael@0: FontRec search(NULL, fontID, glyphID); michael@0: *index = CanonicalFonts().find(search); michael@0: if (*index >= 0) { michael@0: return true; michael@0: } michael@0: search.fGlyphID = 0; michael@0: *index = CanonicalFonts().find(search); michael@0: return false; michael@0: } michael@0: michael@0: SkPDFFont::SkPDFFont(SkAdvancedTypefaceMetrics* info, SkTypeface* typeface, michael@0: SkPDFDict* relatedFontDescriptor) michael@0: : SkPDFDict("Font"), michael@0: fTypeface(ref_or_default(typeface)), michael@0: fFirstGlyphID(1), michael@0: fLastGlyphID(info ? info->fLastGlyphID : 0), michael@0: fFontInfo(SkSafeRef(info)), michael@0: fDescriptor(SkSafeRef(relatedFontDescriptor)) { michael@0: if (info == NULL) { michael@0: fFontType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font; michael@0: } else if (info->fMultiMaster) { michael@0: fFontType = SkAdvancedTypefaceMetrics::kOther_Font; michael@0: } else { michael@0: fFontType = info->fType; michael@0: } michael@0: } michael@0: michael@0: // static michael@0: SkPDFFont* SkPDFFont::Create(SkAdvancedTypefaceMetrics* info, michael@0: SkTypeface* typeface, uint16_t glyphID, michael@0: SkPDFDict* relatedFontDescriptor) { michael@0: SkAdvancedTypefaceMetrics::FontType type = michael@0: info ? info->fType : SkAdvancedTypefaceMetrics::kNotEmbeddable_Font; michael@0: michael@0: if (info && info->fMultiMaster) { michael@0: NOT_IMPLEMENTED(true, true); michael@0: return new SkPDFType3Font(info, michael@0: typeface, michael@0: glyphID); michael@0: } michael@0: if (type == SkAdvancedTypefaceMetrics::kType1CID_Font || michael@0: type == SkAdvancedTypefaceMetrics::kTrueType_Font) { michael@0: SkASSERT(relatedFontDescriptor == NULL); michael@0: return new SkPDFType0Font(info, typeface); michael@0: } michael@0: if (type == SkAdvancedTypefaceMetrics::kType1_Font) { michael@0: return new SkPDFType1Font(info, michael@0: typeface, michael@0: glyphID, michael@0: relatedFontDescriptor); michael@0: } michael@0: michael@0: SkASSERT(type == SkAdvancedTypefaceMetrics::kCFF_Font || michael@0: type == SkAdvancedTypefaceMetrics::kOther_Font || michael@0: type == SkAdvancedTypefaceMetrics::kNotEmbeddable_Font); michael@0: michael@0: return new SkPDFType3Font(info, typeface, glyphID); michael@0: } michael@0: michael@0: SkAdvancedTypefaceMetrics* SkPDFFont::fontInfo() { michael@0: return fFontInfo.get(); michael@0: } michael@0: michael@0: void SkPDFFont::setFontInfo(SkAdvancedTypefaceMetrics* info) { michael@0: if (info == NULL || info == fFontInfo.get()) { michael@0: return; michael@0: } michael@0: fFontInfo.reset(info); michael@0: SkSafeRef(info); michael@0: } michael@0: michael@0: uint16_t SkPDFFont::firstGlyphID() const { michael@0: return fFirstGlyphID; michael@0: } michael@0: michael@0: uint16_t SkPDFFont::lastGlyphID() const { michael@0: return fLastGlyphID; michael@0: } michael@0: michael@0: void SkPDFFont::setLastGlyphID(uint16_t glyphID) { michael@0: fLastGlyphID = glyphID; michael@0: } michael@0: michael@0: void SkPDFFont::addResource(SkPDFObject* object) { michael@0: SkASSERT(object != NULL); michael@0: fResources.push(object); michael@0: object->ref(); michael@0: } michael@0: michael@0: SkPDFDict* SkPDFFont::getFontDescriptor() { michael@0: return fDescriptor.get(); michael@0: } michael@0: michael@0: void SkPDFFont::setFontDescriptor(SkPDFDict* descriptor) { michael@0: fDescriptor.reset(descriptor); michael@0: SkSafeRef(descriptor); michael@0: } michael@0: michael@0: bool SkPDFFont::addCommonFontDescriptorEntries(int16_t defaultWidth) { michael@0: if (fDescriptor.get() == NULL) { michael@0: return false; michael@0: } michael@0: michael@0: const uint16_t emSize = fFontInfo->fEmSize; michael@0: michael@0: fDescriptor->insertName("FontName", fFontInfo->fFontName); michael@0: fDescriptor->insertInt("Flags", fFontInfo->fStyle | kPdfSymbolic); michael@0: fDescriptor->insertScalar("Ascent", michael@0: scaleFromFontUnits(fFontInfo->fAscent, emSize)); michael@0: fDescriptor->insertScalar("Descent", michael@0: scaleFromFontUnits(fFontInfo->fDescent, emSize)); michael@0: fDescriptor->insertScalar("StemV", michael@0: scaleFromFontUnits(fFontInfo->fStemV, emSize)); michael@0: fDescriptor->insertScalar("CapHeight", michael@0: scaleFromFontUnits(fFontInfo->fCapHeight, emSize)); michael@0: fDescriptor->insertInt("ItalicAngle", fFontInfo->fItalicAngle); michael@0: fDescriptor->insert("FontBBox", makeFontBBox(fFontInfo->fBBox, michael@0: fFontInfo->fEmSize))->unref(); michael@0: michael@0: if (defaultWidth > 0) { michael@0: fDescriptor->insertScalar("MissingWidth", michael@0: scaleFromFontUnits(defaultWidth, emSize)); michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: void SkPDFFont::adjustGlyphRangeForSingleByteEncoding(int16_t glyphID) { michael@0: // Single byte glyph encoding supports a max of 255 glyphs. michael@0: fFirstGlyphID = glyphID - (glyphID - 1) % 255; michael@0: if (fLastGlyphID > fFirstGlyphID + 255 - 1) { michael@0: fLastGlyphID = fFirstGlyphID + 255 - 1; michael@0: } michael@0: } michael@0: michael@0: bool SkPDFFont::FontRec::operator==(const SkPDFFont::FontRec& b) const { michael@0: if (fFontID != b.fFontID) { michael@0: return false; michael@0: } michael@0: if (fFont != NULL && b.fFont != NULL) { michael@0: return fFont->fFirstGlyphID == b.fFont->fFirstGlyphID && michael@0: fFont->fLastGlyphID == b.fFont->fLastGlyphID; michael@0: } michael@0: if (fGlyphID == 0 || b.fGlyphID == 0) { michael@0: return true; michael@0: } michael@0: michael@0: if (fFont != NULL) { michael@0: return fFont->fFirstGlyphID <= b.fGlyphID && michael@0: b.fGlyphID <= fFont->fLastGlyphID; michael@0: } else if (b.fFont != NULL) { michael@0: return b.fFont->fFirstGlyphID <= fGlyphID && michael@0: fGlyphID <= b.fFont->fLastGlyphID; michael@0: } michael@0: return fGlyphID == b.fGlyphID; michael@0: } michael@0: michael@0: SkPDFFont::FontRec::FontRec(SkPDFFont* font, uint32_t fontID, uint16_t glyphID) michael@0: : fFont(font), michael@0: fFontID(fontID), michael@0: fGlyphID(glyphID) { michael@0: } michael@0: michael@0: void SkPDFFont::populateToUnicodeTable(const SkPDFGlyphSet* subset) { michael@0: if (fFontInfo == NULL || fFontInfo->fGlyphToUnicode.begin() == NULL) { michael@0: return; michael@0: } michael@0: SkAutoTUnref pdfCmap( michael@0: generate_tounicode_cmap(fFontInfo->fGlyphToUnicode, subset, michael@0: multiByteGlyphs(), firstGlyphID(), michael@0: lastGlyphID())); michael@0: addResource(pdfCmap.get()); michael@0: insert("ToUnicode", new SkPDFObjRef(pdfCmap.get()))->unref(); michael@0: } michael@0: michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: // class SkPDFType0Font michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: SkPDFType0Font::SkPDFType0Font(SkAdvancedTypefaceMetrics* info, michael@0: SkTypeface* typeface) michael@0: : SkPDFFont(info, typeface, NULL) { michael@0: SkDEBUGCODE(fPopulated = false); michael@0: } michael@0: michael@0: SkPDFType0Font::~SkPDFType0Font() {} michael@0: michael@0: SkPDFFont* SkPDFType0Font::getFontSubset(const SkPDFGlyphSet* subset) { michael@0: SkPDFType0Font* newSubset = new SkPDFType0Font(fontInfo(), typeface()); michael@0: newSubset->populate(subset); michael@0: return newSubset; michael@0: } michael@0: michael@0: #ifdef SK_DEBUG michael@0: void SkPDFType0Font::emitObject(SkWStream* stream, SkPDFCatalog* catalog, michael@0: bool indirect) { michael@0: SkASSERT(fPopulated); michael@0: return INHERITED::emitObject(stream, catalog, indirect); michael@0: } michael@0: #endif michael@0: michael@0: bool SkPDFType0Font::populate(const SkPDFGlyphSet* subset) { michael@0: insertName("Subtype", "Type0"); michael@0: insertName("BaseFont", fontInfo()->fFontName); michael@0: insertName("Encoding", "Identity-H"); michael@0: michael@0: SkAutoTUnref newCIDFont( michael@0: new SkPDFCIDFont(fontInfo(), typeface(), subset)); michael@0: addResource(newCIDFont.get()); michael@0: SkAutoTUnref descendantFonts(new SkPDFArray()); michael@0: descendantFonts->append(new SkPDFObjRef(newCIDFont.get()))->unref(); michael@0: insert("DescendantFonts", descendantFonts.get()); michael@0: michael@0: populateToUnicodeTable(subset); michael@0: michael@0: SkDEBUGCODE(fPopulated = true); michael@0: return true; michael@0: } michael@0: michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: // class SkPDFCIDFont michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: SkPDFCIDFont::SkPDFCIDFont(SkAdvancedTypefaceMetrics* info, michael@0: SkTypeface* typeface, const SkPDFGlyphSet* subset) michael@0: : SkPDFFont(info, typeface, NULL) { michael@0: populate(subset); michael@0: } michael@0: michael@0: SkPDFCIDFont::~SkPDFCIDFont() {} michael@0: michael@0: bool SkPDFCIDFont::addFontDescriptor(int16_t defaultWidth, michael@0: const SkTDArray* subset) { michael@0: SkAutoTUnref descriptor(new SkPDFDict("FontDescriptor")); michael@0: setFontDescriptor(descriptor.get()); michael@0: addResource(descriptor.get()); michael@0: michael@0: switch (getType()) { michael@0: case SkAdvancedTypefaceMetrics::kTrueType_Font: { michael@0: SkASSERT(subset); michael@0: // Font subsetting michael@0: SkPDFStream* rawStream = NULL; michael@0: int fontSize = get_subset_font_stream(fontInfo()->fFontName.c_str(), michael@0: typeface(), michael@0: *subset, michael@0: &rawStream); michael@0: SkASSERT(fontSize); michael@0: SkASSERT(rawStream); michael@0: SkAutoTUnref fontStream(rawStream); michael@0: addResource(fontStream.get()); michael@0: michael@0: fontStream->insertInt("Length1", fontSize); michael@0: descriptor->insert("FontFile2", michael@0: new SkPDFObjRef(fontStream.get()))->unref(); michael@0: break; michael@0: } michael@0: case SkAdvancedTypefaceMetrics::kCFF_Font: michael@0: case SkAdvancedTypefaceMetrics::kType1CID_Font: { michael@0: int ttcIndex; michael@0: SkAutoTUnref fontData(typeface()->openStream(&ttcIndex)); michael@0: SkAutoTUnref fontStream( michael@0: new SkPDFStream(fontData.get())); michael@0: addResource(fontStream.get()); michael@0: michael@0: if (getType() == SkAdvancedTypefaceMetrics::kCFF_Font) { michael@0: fontStream->insertName("Subtype", "Type1C"); michael@0: } else { michael@0: fontStream->insertName("Subtype", "CIDFontType0c"); michael@0: } michael@0: descriptor->insert("FontFile3", michael@0: new SkPDFObjRef(fontStream.get()))->unref(); michael@0: break; michael@0: } michael@0: default: michael@0: SkASSERT(false); michael@0: } michael@0: michael@0: insert("FontDescriptor", new SkPDFObjRef(descriptor.get()))->unref(); michael@0: return addCommonFontDescriptorEntries(defaultWidth); michael@0: } michael@0: michael@0: bool SkPDFCIDFont::populate(const SkPDFGlyphSet* subset) { michael@0: // Generate new font metrics with advance info for true type fonts. michael@0: if (fontInfo()->fType == SkAdvancedTypefaceMetrics::kTrueType_Font) { michael@0: // Generate glyph id array. michael@0: SkTDArray glyphIDs; michael@0: if (subset) { michael@0: // Always include glyph 0. michael@0: if (!subset->has(0)) { michael@0: glyphIDs.push(0); michael@0: } michael@0: subset->exportTo(&glyphIDs); michael@0: } michael@0: michael@0: SkAdvancedTypefaceMetrics::PerGlyphInfo info; michael@0: info = SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo; michael@0: info = SkTBitOr( michael@0: info, SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo); michael@0: uint32_t* glyphs = (glyphIDs.count() == 0) ? NULL : glyphIDs.begin(); michael@0: uint32_t glyphsCount = glyphs ? glyphIDs.count() : 0; michael@0: SkAutoTUnref fontMetrics( michael@0: typeface()->getAdvancedTypefaceMetrics(info, glyphs, glyphsCount)); michael@0: setFontInfo(fontMetrics.get()); michael@0: addFontDescriptor(0, &glyphIDs); michael@0: } else { michael@0: // Other CID fonts michael@0: addFontDescriptor(0, NULL); michael@0: } michael@0: michael@0: insertName("BaseFont", fontInfo()->fFontName); michael@0: michael@0: if (getType() == SkAdvancedTypefaceMetrics::kType1CID_Font) { michael@0: insertName("Subtype", "CIDFontType0"); michael@0: } else if (getType() == SkAdvancedTypefaceMetrics::kTrueType_Font) { michael@0: insertName("Subtype", "CIDFontType2"); michael@0: insertName("CIDToGIDMap", "Identity"); michael@0: } else { michael@0: SkASSERT(false); michael@0: } michael@0: michael@0: SkAutoTUnref sysInfo(new SkPDFDict); michael@0: sysInfo->insert("Registry", new SkPDFString("Adobe"))->unref(); michael@0: sysInfo->insert("Ordering", new SkPDFString("Identity"))->unref(); michael@0: sysInfo->insertInt("Supplement", 0); michael@0: insert("CIDSystemInfo", sysInfo.get()); michael@0: michael@0: if (fontInfo()->fGlyphWidths.get()) { michael@0: int16_t defaultWidth = 0; michael@0: SkAutoTUnref widths( michael@0: composeAdvanceData(fontInfo()->fGlyphWidths.get(), michael@0: fontInfo()->fEmSize, &appendWidth, michael@0: &defaultWidth)); michael@0: if (widths->size()) michael@0: insert("W", widths.get()); michael@0: if (defaultWidth != 0) { michael@0: insertScalar("DW", scaleFromFontUnits(defaultWidth, michael@0: fontInfo()->fEmSize)); michael@0: } michael@0: } michael@0: if (fontInfo()->fVerticalMetrics.get()) { michael@0: struct SkAdvancedTypefaceMetrics::VerticalMetric defaultAdvance; michael@0: defaultAdvance.fVerticalAdvance = 0; michael@0: defaultAdvance.fOriginXDisp = 0; michael@0: defaultAdvance.fOriginYDisp = 0; michael@0: SkAutoTUnref advances( michael@0: composeAdvanceData(fontInfo()->fVerticalMetrics.get(), michael@0: fontInfo()->fEmSize, &appendVerticalAdvance, michael@0: &defaultAdvance)); michael@0: if (advances->size()) michael@0: insert("W2", advances.get()); michael@0: if (defaultAdvance.fVerticalAdvance || michael@0: defaultAdvance.fOriginXDisp || michael@0: defaultAdvance.fOriginYDisp) { michael@0: insert("DW2", appendVerticalAdvance(defaultAdvance, michael@0: fontInfo()->fEmSize, michael@0: new SkPDFArray))->unref(); michael@0: } michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: // class SkPDFType1Font michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: SkPDFType1Font::SkPDFType1Font(SkAdvancedTypefaceMetrics* info, michael@0: SkTypeface* typeface, michael@0: uint16_t glyphID, michael@0: SkPDFDict* relatedFontDescriptor) michael@0: : SkPDFFont(info, typeface, relatedFontDescriptor) { michael@0: populate(glyphID); michael@0: } michael@0: michael@0: SkPDFType1Font::~SkPDFType1Font() {} michael@0: michael@0: bool SkPDFType1Font::addFontDescriptor(int16_t defaultWidth) { michael@0: if (getFontDescriptor() != NULL) { michael@0: SkPDFDict* descriptor = getFontDescriptor(); michael@0: addResource(descriptor); michael@0: insert("FontDescriptor", new SkPDFObjRef(descriptor))->unref(); michael@0: return true; michael@0: } michael@0: michael@0: SkAutoTUnref descriptor(new SkPDFDict("FontDescriptor")); michael@0: setFontDescriptor(descriptor.get()); michael@0: michael@0: int ttcIndex; michael@0: size_t header SK_INIT_TO_AVOID_WARNING; michael@0: size_t data SK_INIT_TO_AVOID_WARNING; michael@0: size_t trailer SK_INIT_TO_AVOID_WARNING; michael@0: SkAutoTUnref rawFontData(typeface()->openStream(&ttcIndex)); michael@0: SkStream* fontData = handleType1Stream(rawFontData.get(), &header, &data, michael@0: &trailer); michael@0: if (fontData == NULL) { michael@0: return false; michael@0: } michael@0: SkAutoTUnref fontStream(new SkPDFStream(fontData)); michael@0: addResource(fontStream.get()); michael@0: fontStream->insertInt("Length1", header); michael@0: fontStream->insertInt("Length2", data); michael@0: fontStream->insertInt("Length3", trailer); michael@0: descriptor->insert("FontFile", new SkPDFObjRef(fontStream.get()))->unref(); michael@0: michael@0: addResource(descriptor.get()); michael@0: insert("FontDescriptor", new SkPDFObjRef(descriptor.get()))->unref(); michael@0: michael@0: return addCommonFontDescriptorEntries(defaultWidth); michael@0: } michael@0: michael@0: bool SkPDFType1Font::populate(int16_t glyphID) { michael@0: SkASSERT(!fontInfo()->fVerticalMetrics.get()); michael@0: SkASSERT(fontInfo()->fGlyphWidths.get()); michael@0: michael@0: adjustGlyphRangeForSingleByteEncoding(glyphID); michael@0: michael@0: int16_t defaultWidth = 0; michael@0: const SkAdvancedTypefaceMetrics::WidthRange* widthRangeEntry = NULL; michael@0: const SkAdvancedTypefaceMetrics::WidthRange* widthEntry; michael@0: for (widthEntry = fontInfo()->fGlyphWidths.get(); michael@0: widthEntry != NULL; michael@0: widthEntry = widthEntry->fNext.get()) { michael@0: switch (widthEntry->fType) { michael@0: case SkAdvancedTypefaceMetrics::WidthRange::kDefault: michael@0: defaultWidth = widthEntry->fAdvance[0]; michael@0: break; michael@0: case SkAdvancedTypefaceMetrics::WidthRange::kRun: michael@0: SkASSERT(false); michael@0: break; michael@0: case SkAdvancedTypefaceMetrics::WidthRange::kRange: michael@0: SkASSERT(widthRangeEntry == NULL); michael@0: widthRangeEntry = widthEntry; michael@0: break; michael@0: } michael@0: } michael@0: michael@0: if (!addFontDescriptor(defaultWidth)) { michael@0: return false; michael@0: } michael@0: michael@0: insertName("Subtype", "Type1"); michael@0: insertName("BaseFont", fontInfo()->fFontName); michael@0: michael@0: addWidthInfoFromRange(defaultWidth, widthRangeEntry); michael@0: michael@0: SkAutoTUnref encoding(new SkPDFDict("Encoding")); michael@0: insert("Encoding", encoding.get()); michael@0: michael@0: SkAutoTUnref encDiffs(new SkPDFArray); michael@0: encoding->insert("Differences", encDiffs.get()); michael@0: michael@0: encDiffs->reserve(lastGlyphID() - firstGlyphID() + 2); michael@0: encDiffs->appendInt(1); michael@0: for (int gID = firstGlyphID(); gID <= lastGlyphID(); gID++) { michael@0: encDiffs->appendName(fontInfo()->fGlyphNames->get()[gID].c_str()); michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: void SkPDFType1Font::addWidthInfoFromRange( michael@0: int16_t defaultWidth, michael@0: const SkAdvancedTypefaceMetrics::WidthRange* widthRangeEntry) { michael@0: SkAutoTUnref widthArray(new SkPDFArray()); michael@0: int firstChar = 0; michael@0: if (widthRangeEntry) { michael@0: const uint16_t emSize = fontInfo()->fEmSize; michael@0: int startIndex = firstGlyphID() - widthRangeEntry->fStartId; michael@0: int endIndex = startIndex + lastGlyphID() - firstGlyphID() + 1; michael@0: if (startIndex < 0) michael@0: startIndex = 0; michael@0: if (endIndex > widthRangeEntry->fAdvance.count()) michael@0: endIndex = widthRangeEntry->fAdvance.count(); michael@0: if (widthRangeEntry->fStartId == 0) { michael@0: appendWidth(widthRangeEntry->fAdvance[0], emSize, widthArray.get()); michael@0: } else { michael@0: firstChar = startIndex + widthRangeEntry->fStartId; michael@0: } michael@0: for (int i = startIndex; i < endIndex; i++) { michael@0: appendWidth(widthRangeEntry->fAdvance[i], emSize, widthArray.get()); michael@0: } michael@0: } else { michael@0: appendWidth(defaultWidth, 1000, widthArray.get()); michael@0: } michael@0: insertInt("FirstChar", firstChar); michael@0: insertInt("LastChar", firstChar + widthArray->size() - 1); michael@0: insert("Widths", widthArray.get()); michael@0: } michael@0: michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: // class SkPDFType3Font michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: SkPDFType3Font::SkPDFType3Font(SkAdvancedTypefaceMetrics* info, michael@0: SkTypeface* typeface, michael@0: uint16_t glyphID) michael@0: : SkPDFFont(info, typeface, NULL) { michael@0: populate(glyphID); michael@0: } michael@0: michael@0: SkPDFType3Font::~SkPDFType3Font() {} michael@0: michael@0: bool SkPDFType3Font::populate(int16_t glyphID) { michael@0: SkPaint paint; michael@0: paint.setTypeface(typeface()); michael@0: paint.setTextSize(1000); michael@0: SkAutoGlyphCache autoCache(paint, NULL, NULL); michael@0: SkGlyphCache* cache = autoCache.getCache(); michael@0: // If fLastGlyphID isn't set (because there is not fFontInfo), look it up. michael@0: if (lastGlyphID() == 0) { michael@0: setLastGlyphID(cache->getGlyphCount() - 1); michael@0: } michael@0: michael@0: adjustGlyphRangeForSingleByteEncoding(glyphID); michael@0: michael@0: insertName("Subtype", "Type3"); michael@0: // Flip about the x-axis and scale by 1/1000. michael@0: SkMatrix fontMatrix; michael@0: fontMatrix.setScale(SkScalarInvert(1000), -SkScalarInvert(1000)); michael@0: insert("FontMatrix", SkPDFUtils::MatrixToArray(fontMatrix))->unref(); michael@0: michael@0: SkAutoTUnref charProcs(new SkPDFDict); michael@0: insert("CharProcs", charProcs.get()); michael@0: michael@0: SkAutoTUnref encoding(new SkPDFDict("Encoding")); michael@0: insert("Encoding", encoding.get()); michael@0: michael@0: SkAutoTUnref encDiffs(new SkPDFArray); michael@0: encoding->insert("Differences", encDiffs.get()); michael@0: encDiffs->reserve(lastGlyphID() - firstGlyphID() + 2); michael@0: encDiffs->appendInt(1); michael@0: michael@0: SkAutoTUnref widthArray(new SkPDFArray()); michael@0: michael@0: SkIRect bbox = SkIRect::MakeEmpty(); michael@0: for (int gID = firstGlyphID(); gID <= lastGlyphID(); gID++) { michael@0: SkString characterName; michael@0: characterName.printf("gid%d", gID); michael@0: encDiffs->appendName(characterName.c_str()); michael@0: michael@0: const SkGlyph& glyph = cache->getGlyphIDMetrics(gID); michael@0: widthArray->appendScalar(SkFixedToScalar(glyph.fAdvanceX)); michael@0: SkIRect glyphBBox = SkIRect::MakeXYWH(glyph.fLeft, glyph.fTop, michael@0: glyph.fWidth, glyph.fHeight); michael@0: bbox.join(glyphBBox); michael@0: michael@0: SkDynamicMemoryWStream content; michael@0: setGlyphWidthAndBoundingBox(SkFixedToScalar(glyph.fAdvanceX), glyphBBox, michael@0: &content); michael@0: const SkPath* path = cache->findPath(glyph); michael@0: if (path) { michael@0: SkPDFUtils::EmitPath(*path, paint.getStyle(), &content); michael@0: SkPDFUtils::PaintPath(paint.getStyle(), path->getFillType(), michael@0: &content); michael@0: } michael@0: SkAutoTUnref glyphStream(new SkMemoryStream()); michael@0: glyphStream->setData(content.copyToData())->unref(); michael@0: michael@0: SkAutoTUnref glyphDescription( michael@0: new SkPDFStream(glyphStream.get())); michael@0: addResource(glyphDescription.get()); michael@0: charProcs->insert(characterName.c_str(), michael@0: new SkPDFObjRef(glyphDescription.get()))->unref(); michael@0: } michael@0: michael@0: insert("FontBBox", makeFontBBox(bbox, 1000))->unref(); michael@0: insertInt("FirstChar", 1); michael@0: insertInt("LastChar", lastGlyphID() - firstGlyphID() + 1); michael@0: insert("Widths", widthArray.get()); michael@0: insertName("CIDToGIDMap", "Identity"); michael@0: michael@0: populateToUnicodeTable(NULL); michael@0: return true; michael@0: }