2 * Copyright 2011 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
11 #include "SkFontHost.h"
12 #include "SkGlyphCache.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"
24 #include "SkTypefacePriv.h"
28 #if defined (SK_SFNTLY_SUBSETTER)
29 #include SK_SFNTLY_SUBSETTER
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;
39 ///////////////////////////////////////////////////////////////////////////////
40 // File-Local Functions
41 ///////////////////////////////////////////////////////////////////////////////
43 bool parsePFBSection(const uint8_t** src, size_t* len, int sectionType,
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) {
52 } else if (buf[1] == 3) {
54 } else if (*len < 6) {
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) {
64 *src = *src + consumed;
65 *len = *len - consumed;
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);
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).
84 * This function assumes that src is NUL terminated, but the NUL
85 * termination is not included in size.
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");
96 dataPos += strlen("eexec");
97 while ((*dataPos == '\n' || *dataPos == '\r' || *dataPos == ' ') &&
101 *headerLen = dataPos - src;
103 const char* trailerPos = strstr(dataPos, "cleartomark");
108 for (trailerPos--; trailerPos > dataPos && zeroCount < 512; trailerPos--) {
109 if (*trailerPos == '\n' || *trailerPos == '\r' || *trailerPos == ' ') {
111 } else if (*trailerPos == '0') {
117 if (zeroCount != 512) {
121 *hexDataLen = trailerPos - src - *headerLen;
122 *trailerLen = size - *headerLen - *hexDataLen;
124 // Verify that the data section is hex encoded and count the bytes.
126 for (; dataPos < trailerPos; dataPos++) {
127 if (isspace(*dataPos)) {
130 if (!isxdigit(*dataPos)) {
135 *dataLen = (nibbles + 1) / 2;
140 int8_t hexToBin(uint8_t c) {
143 } else if (c <= '9') {
145 } else if (c <= 'F') {
147 } else if (c <= 'f') {
153 static SkData* handle_type1_stream(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;
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);
172 while (read < srcLen) {
173 size_t got = srcStream->read((void *)staticStream->getAtPos(),
179 staticStream->seek(read);
182 ((uint8_t *)src)[srcLen] = 0;
184 static const size_t kBufSize = 4096;
185 uint8_t buf[kBufSize];
187 while ((amount = srcStream->read(buf, kBufSize)) > 0) {
188 dynamicStream.write(buf, amount);
191 dynamicStream.write(&amount, 1); // NULL terminator.
192 data = dynamicStream.copyToData();
194 srcLen = data->size() - 1;
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 static const int kPFBSectionHeaderLength = 6;
203 const size_t length = *headerLen + *dataLen + *trailerLen;
204 SkASSERT(length > 0);
205 SkASSERT(length + (2 * kPFBSectionHeaderLength) <= srcLen);
207 SkData* data = SkData::NewUninitialized(length);
209 const uint8_t* const srcHeader = src + kPFBSectionHeaderLength;
210 // There is a six-byte section header before header and data
211 // (but not trailer) that we're not going to copy.
212 const uint8_t* const srcData = srcHeader + *headerLen + kPFBSectionHeaderLength;
213 const uint8_t* const srcTrailer = srcData + *headerLen;
215 uint8_t* const resultHeader = (uint8_t*)data->writable_data();
216 uint8_t* const resultData = resultHeader + *headerLen;
217 uint8_t* const resultTrailer = resultData + *dataLen;
219 SkASSERT(resultTrailer + *trailerLen == resultHeader + length);
221 memcpy(resultHeader, srcHeader, *headerLen);
222 memcpy(resultData, srcData, *dataLen);
223 memcpy(resultTrailer, srcTrailer, *trailerLen);
228 // A PFA has to be converted for PDF.
230 if (parsePFA((const char*)src, srcLen, headerLen, &hexDataLen, dataLen,
232 const size_t length = *headerLen + *dataLen + *trailerLen;
233 SkASSERT(length > 0);
234 SkAutoTMalloc<uint8_t> buffer(length);
236 memcpy(buffer.get(), src, *headerLen);
237 uint8_t* const resultData = &(buffer[*headerLen]);
239 const uint8_t* hexData = src + *headerLen;
240 const uint8_t* trailer = hexData + hexDataLen;
241 size_t outputOffset = 0;
242 uint8_t dataByte = 0; // To hush compiler.
243 bool highNibble = true;
244 for (; hexData < trailer; hexData++) {
245 int8_t curNibble = hexToBin(*hexData);
250 dataByte = curNibble << 4;
253 dataByte |= curNibble;
255 resultData[outputOffset++] = dataByte;
259 resultData[outputOffset++] = dataByte;
261 SkASSERT(outputOffset == *dataLen);
263 uint8_t* const resultTrailer = &(buffer[*headerLen + outputOffset]);
264 memcpy(resultTrailer, src + *headerLen + hexDataLen, *trailerLen);
266 return SkData::NewFromMalloc(buffer.detach(), length);
271 // scale from em-units to base-1000, returning as a SkScalar
272 SkScalar scaleFromFontUnits(int16_t val, uint16_t emSize) {
273 SkScalar scaled = SkIntToScalar(val);
274 if (emSize == 1000) {
277 return SkScalarMulDiv(scaled, 1000, emSize);
281 void setGlyphWidthAndBoundingBox(SkScalar width, SkIRect box,
282 SkWStream* content) {
283 // Specify width and bounding box for the glyph.
284 SkPDFScalar::Append(width, content);
285 content->writeText(" 0 ");
286 content->writeDecAsText(box.fLeft);
287 content->writeText(" ");
288 content->writeDecAsText(box.fTop);
289 content->writeText(" ");
290 content->writeDecAsText(box.fRight);
291 content->writeText(" ");
292 content->writeDecAsText(box.fBottom);
293 content->writeText(" d1\n");
296 SkPDFArray* makeFontBBox(SkIRect glyphBBox, uint16_t emSize) {
297 SkPDFArray* bbox = new SkPDFArray;
299 bbox->appendScalar(scaleFromFontUnits(glyphBBox.fLeft, emSize));
300 bbox->appendScalar(scaleFromFontUnits(glyphBBox.fBottom, emSize));
301 bbox->appendScalar(scaleFromFontUnits(glyphBBox.fRight, emSize));
302 bbox->appendScalar(scaleFromFontUnits(glyphBBox.fTop, emSize));
306 SkPDFArray* appendWidth(const int16_t& width, uint16_t emSize,
308 array->appendScalar(scaleFromFontUnits(width, emSize));
312 SkPDFArray* appendVerticalAdvance(
313 const SkAdvancedTypefaceMetrics::VerticalMetric& advance,
314 uint16_t emSize, SkPDFArray* array) {
315 appendWidth(advance.fVerticalAdvance, emSize, array);
316 appendWidth(advance.fOriginXDisp, emSize, array);
317 appendWidth(advance.fOriginYDisp, emSize, array);
321 template <typename Data>
322 SkPDFArray* composeAdvanceData(
323 SkAdvancedTypefaceMetrics::AdvanceMetric<Data>* advanceInfo,
325 SkPDFArray* (*appendAdvance)(const Data& advance, uint16_t emSize,
327 Data* defaultAdvance) {
328 SkPDFArray* result = new SkPDFArray();
329 for (; advanceInfo != NULL; advanceInfo = advanceInfo->fNext.get()) {
330 switch (advanceInfo->fType) {
331 case SkAdvancedTypefaceMetrics::WidthRange::kDefault: {
332 SkASSERT(advanceInfo->fAdvance.count() == 1);
333 *defaultAdvance = advanceInfo->fAdvance[0];
336 case SkAdvancedTypefaceMetrics::WidthRange::kRange: {
337 SkAutoTUnref<SkPDFArray> advanceArray(new SkPDFArray());
338 for (int j = 0; j < advanceInfo->fAdvance.count(); j++)
339 appendAdvance(advanceInfo->fAdvance[j], emSize,
341 result->appendInt(advanceInfo->fStartId);
342 result->append(advanceArray.get());
345 case SkAdvancedTypefaceMetrics::WidthRange::kRun: {
346 SkASSERT(advanceInfo->fAdvance.count() == 1);
347 result->appendInt(advanceInfo->fStartId);
348 result->appendInt(advanceInfo->fEndId);
349 appendAdvance(advanceInfo->fAdvance[0], emSize, result);
359 static void append_tounicode_header(SkDynamicMemoryWStream* cmap,
360 uint16_t firstGlyphID,
361 uint16_t lastGlyphID) {
362 // 12 dict begin: 12 is an Adobe-suggested value. Shall not change.
363 // It's there to prevent old version Adobe Readers from malfunctioning.
364 const char* kHeader =
365 "/CIDInit /ProcSet findresource begin\n"
368 cmap->writeText(kHeader);
370 // The /CIDSystemInfo must be consistent to the one in
371 // SkPDFFont::populateCIDFont().
372 // We can not pass over the system info object here because the format is
373 // different. This is not a reference object.
374 const char* kSysInfo =
376 "<< /Registry (Adobe)\n"
380 cmap->writeText(kSysInfo);
382 // The CMapName must be consistent to /CIDSystemInfo above.
383 // /CMapType 2 means ToUnicode.
384 // Codespace range just tells the PDF processor the valid range.
385 const char* kTypeInfoHeader =
386 "/CMapName /Adobe-Identity-UCS def\n"
388 "1 begincodespacerange\n";
389 cmap->writeText(kTypeInfoHeader);
391 // e.g. "<0000> <FFFF>\n"
393 range.appendf("<%04X> <%04X>\n", firstGlyphID, lastGlyphID);
394 cmap->writeText(range.c_str());
396 const char* kTypeInfoFooter = "endcodespacerange\n";
397 cmap->writeText(kTypeInfoFooter);
400 static void append_cmap_footer(SkDynamicMemoryWStream* cmap) {
401 const char* kFooter =
403 "CMapName currentdict /CMap defineresource pop\n"
406 cmap->writeText(kFooter);
420 static void append_bfchar_section(const SkTDArray<BFChar>& bfchar,
421 SkDynamicMemoryWStream* cmap) {
422 // PDF spec defines that every bf* list can have at most 100 entries.
423 for (int i = 0; i < bfchar.count(); i += 100) {
424 int count = bfchar.count() - i;
425 count = SkMin32(count, 100);
426 cmap->writeDecAsText(count);
427 cmap->writeText(" beginbfchar\n");
428 for (int j = 0; j < count; ++j) {
429 cmap->writeText("<");
430 cmap->writeHexAsText(bfchar[i + j].fGlyphId, 4);
431 cmap->writeText("> <");
432 cmap->writeHexAsText(bfchar[i + j].fUnicode, 4);
433 cmap->writeText(">\n");
435 cmap->writeText("endbfchar\n");
439 static void append_bfrange_section(const SkTDArray<BFRange>& bfrange,
440 SkDynamicMemoryWStream* cmap) {
441 // PDF spec defines that every bf* list can have at most 100 entries.
442 for (int i = 0; i < bfrange.count(); i += 100) {
443 int count = bfrange.count() - i;
444 count = SkMin32(count, 100);
445 cmap->writeDecAsText(count);
446 cmap->writeText(" beginbfrange\n");
447 for (int j = 0; j < count; ++j) {
448 cmap->writeText("<");
449 cmap->writeHexAsText(bfrange[i + j].fStart, 4);
450 cmap->writeText("> <");
451 cmap->writeHexAsText(bfrange[i + j].fEnd, 4);
452 cmap->writeText("> <");
453 cmap->writeHexAsText(bfrange[i + j].fUnicode, 4);
454 cmap->writeText(">\n");
456 cmap->writeText("endbfrange\n");
460 // Generate <bfchar> and <bfrange> table according to PDF spec 1.4 and Adobe
462 // The function is not static so we can test it in unit tests.
464 // Current implementation guarantees bfchar and bfrange entries do not overlap.
466 // Current implementation does not attempt aggresive optimizations against
467 // following case because the specification is not clear.
469 // 4 beginbfchar 1 beginbfchar
470 // <0003> <0013> <0020> <0014>
471 // <0005> <0015> to endbfchar
472 // <0007> <0017> 1 beginbfrange
473 // <0020> <0014> <0003> <0007> <0013>
474 // endbfchar endbfrange
476 // Adobe Technote 5014 said: "Code mappings (unlike codespace ranges) may
477 // overlap, but succeeding maps supersede preceding maps."
479 // In case of searching text in PDF, bfrange will have higher precedence so
480 // typing char id 0x0014 in search box will get glyph id 0x0004 first. However,
481 // the spec does not mention how will this kind of conflict being resolved.
483 // For the worst case (having 65536 continuous unicode and we use every other
484 // one of them), the possible savings by aggressive optimization is 416KB
485 // pre-compressed and does not provide enough motivation for implementation.
487 // FIXME: this should be in a header so that it is separately testable
488 // ( see caller in tests/ToUnicode.cpp )
489 void append_cmap_sections(const SkTDArray<SkUnichar>& glyphToUnicode,
490 const SkPDFGlyphSet* subset,
491 SkDynamicMemoryWStream* cmap,
492 bool multiByteGlyphs,
493 uint16_t firstGlyphID,
494 uint16_t lastGlyphID);
496 void append_cmap_sections(const SkTDArray<SkUnichar>& glyphToUnicode,
497 const SkPDFGlyphSet* subset,
498 SkDynamicMemoryWStream* cmap,
499 bool multiByteGlyphs,
500 uint16_t firstGlyphID,
501 uint16_t lastGlyphID) {
502 if (glyphToUnicode.isEmpty()) {
506 if (!multiByteGlyphs) {
507 glyphOffset = firstGlyphID - 1;
510 SkTDArray<BFChar> bfcharEntries;
511 SkTDArray<BFRange> bfrangeEntries;
513 BFRange currentRangeEntry = {0, 0, 0};
514 bool rangeEmpty = true;
516 SkMin32(lastGlyphID + 1, glyphToUnicode.count()) - glyphOffset;
518 for (int i = firstGlyphID - glyphOffset; i < limit + 1; ++i) {
519 bool inSubset = i < limit &&
520 (subset == NULL || subset->has(i + glyphOffset));
522 // PDF spec requires bfrange not changing the higher byte,
523 // e.g. <1035> <10FF> <2222> is ok, but
524 // <1035> <1100> <2222> is no good
526 i == currentRangeEntry.fEnd + 1 &&
527 i >> 8 == currentRangeEntry.fStart >> 8 &&
529 glyphToUnicode[i + glyphOffset] ==
530 currentRangeEntry.fUnicode + i - currentRangeEntry.fStart;
531 if (!inSubset || !inRange) {
532 if (currentRangeEntry.fEnd > currentRangeEntry.fStart) {
533 bfrangeEntries.push(currentRangeEntry);
535 BFChar* entry = bfcharEntries.append();
536 entry->fGlyphId = currentRangeEntry.fStart;
537 entry->fUnicode = currentRangeEntry.fUnicode;
543 currentRangeEntry.fEnd = i;
545 currentRangeEntry.fStart = i;
546 currentRangeEntry.fUnicode = glyphToUnicode[i + glyphOffset];
552 // The spec requires all bfchar entries for a font must come before bfrange
554 append_bfchar_section(bfcharEntries, cmap);
555 append_bfrange_section(bfrangeEntries, cmap);
558 static SkPDFStream* generate_tounicode_cmap(
559 const SkTDArray<SkUnichar>& glyphToUnicode,
560 const SkPDFGlyphSet* subset,
561 bool multiByteGlyphs,
562 uint16_t firstGlyphID,
563 uint16_t lastGlyphID) {
564 SkDynamicMemoryWStream cmap;
565 if (multiByteGlyphs) {
566 append_tounicode_header(&cmap, firstGlyphID, lastGlyphID);
568 append_tounicode_header(&cmap, 1, lastGlyphID - firstGlyphID + 1);
570 append_cmap_sections(glyphToUnicode, subset, &cmap, multiByteGlyphs,
571 firstGlyphID, lastGlyphID);
572 append_cmap_footer(&cmap);
573 SkAutoTUnref<SkData> cmapData(cmap.copyToData());
574 return new SkPDFStream(cmapData.get());
577 #if defined (SK_SFNTLY_SUBSETTER)
578 static void sk_delete_array(const void* ptr, size_t, void*) {
579 // Use C-style cast to cast away const and cast type simultaneously.
580 delete[] (unsigned char*)ptr;
584 static size_t get_subset_font_stream(const char* fontName,
585 const SkTypeface* typeface,
586 const SkTDArray<uint32_t>& subset,
587 SkPDFStream** fontStream) {
589 SkAutoTUnref<SkStream> fontData(typeface->openStream(&ttcIndex));
590 SkASSERT(fontData.get());
592 size_t fontSize = fontData->getLength();
594 #if defined (SK_SFNTLY_SUBSETTER)
595 // Read font into buffer.
596 SkPDFStream* subsetFontStream = NULL;
597 SkTDArray<unsigned char> originalFont;
598 originalFont.setCount(SkToInt(fontSize));
599 if (fontData->read(originalFont.begin(), fontSize) == fontSize) {
600 unsigned char* subsetFont = NULL;
601 // sfntly requires unsigned int* to be passed in, as far as we know,
602 // unsigned int is equivalent to uint32_t on all platforms.
603 SK_COMPILE_ASSERT(sizeof(unsigned int) == sizeof(uint32_t),
604 unsigned_int_not_32_bits);
605 int subsetFontSize = SfntlyWrapper::SubsetFont(fontName,
606 originalFont.begin(),
611 if (subsetFontSize > 0 && subsetFont != NULL) {
612 SkAutoDataUnref data(SkData::NewWithProc(subsetFont,
616 subsetFontStream = new SkPDFStream(data.get());
617 fontSize = subsetFontSize;
620 if (subsetFontStream) {
621 *fontStream = subsetFontStream;
626 sk_ignore_unused_variable(fontName);
627 sk_ignore_unused_variable(subset);
630 // Fail over: just embed the whole font.
631 *fontStream = new SkPDFStream(fontData.get());
635 ///////////////////////////////////////////////////////////////////////////////
636 // class SkPDFGlyphSet
637 ///////////////////////////////////////////////////////////////////////////////
639 SkPDFGlyphSet::SkPDFGlyphSet() : fBitSet(SK_MaxU16 + 1) {
642 void SkPDFGlyphSet::set(const uint16_t* glyphIDs, int numGlyphs) {
643 for (int i = 0; i < numGlyphs; ++i) {
644 fBitSet.setBit(glyphIDs[i], true);
648 bool SkPDFGlyphSet::has(uint16_t glyphID) const {
649 return fBitSet.isBitSet(glyphID);
652 void SkPDFGlyphSet::merge(const SkPDFGlyphSet& usage) {
653 fBitSet.orBits(usage.fBitSet);
656 void SkPDFGlyphSet::exportTo(SkTDArray<unsigned int>* glyphIDs) const {
657 fBitSet.exportTo(glyphIDs);
660 ///////////////////////////////////////////////////////////////////////////////
661 // class SkPDFGlyphSetMap
662 ///////////////////////////////////////////////////////////////////////////////
663 SkPDFGlyphSetMap::FontGlyphSetPair::FontGlyphSetPair(SkPDFFont* font,
664 SkPDFGlyphSet* glyphSet)
666 fGlyphSet(glyphSet) {
669 SkPDFGlyphSetMap::F2BIter::F2BIter(const SkPDFGlyphSetMap& map) {
673 const SkPDFGlyphSetMap::FontGlyphSetPair* SkPDFGlyphSetMap::F2BIter::next() const {
674 if (fIndex >= fMap->count()) {
677 return &((*fMap)[fIndex++]);
680 void SkPDFGlyphSetMap::F2BIter::reset(const SkPDFGlyphSetMap& map) {
685 SkPDFGlyphSetMap::SkPDFGlyphSetMap() {
688 SkPDFGlyphSetMap::~SkPDFGlyphSetMap() {
692 void SkPDFGlyphSetMap::merge(const SkPDFGlyphSetMap& usage) {
693 for (int i = 0; i < usage.fMap.count(); ++i) {
694 SkPDFGlyphSet* myUsage = getGlyphSetForFont(usage.fMap[i].fFont);
695 myUsage->merge(*(usage.fMap[i].fGlyphSet));
699 void SkPDFGlyphSetMap::reset() {
700 for (int i = 0; i < fMap.count(); ++i) {
701 delete fMap[i].fGlyphSet; // Should not be NULL.
706 void SkPDFGlyphSetMap::noteGlyphUsage(SkPDFFont* font, const uint16_t* glyphIDs,
708 SkPDFGlyphSet* subset = getGlyphSetForFont(font);
710 subset->set(glyphIDs, numGlyphs);
714 SkPDFGlyphSet* SkPDFGlyphSetMap::getGlyphSetForFont(SkPDFFont* font) {
715 int index = fMap.count();
716 for (int i = 0; i < index; ++i) {
717 if (fMap[i].fFont == font) {
718 return fMap[i].fGlyphSet;
722 index = fMap.count() - 1;
723 fMap[index].fFont = font;
724 fMap[index].fGlyphSet = new SkPDFGlyphSet();
725 return fMap[index].fGlyphSet;
728 ///////////////////////////////////////////////////////////////////////////////
730 ///////////////////////////////////////////////////////////////////////////////
732 /* Font subset design: It would be nice to be able to subset fonts
733 * (particularly type 3 fonts), but it's a lot of work and not a priority.
735 * Resources are canonicalized and uniqueified by pointer so there has to be
736 * some additional state indicating which subset of the font is used. It
737 * must be maintained at the page granularity and then combined at the document
738 * granularity. a) change SkPDFFont to fill in its state on demand, kind of
739 * like SkPDFGraphicState. b) maintain a per font glyph usage class in each
740 * page/pdf device. c) in the document, retrieve the per font glyph usage
741 * from each page and combine it and ask for a resource with that subset.
744 SkPDFFont::~SkPDFFont() {
745 SkAutoMutexAcquire lock(CanonicalFontsMutex());
747 for (int i = 0 ; i < CanonicalFonts().count() ; i++) {
748 if (CanonicalFonts()[i].fFont == this) {
753 SkDEBUGCODE(int indexFound;)
754 SkASSERT(index == -1 ||
755 (Find(fTypeface->uniqueID(),
758 index == indexFound));
760 CanonicalFonts().removeShuffle(index);
762 fResources.unrefAll();
765 void SkPDFFont::getResources(const SkTSet<SkPDFObject*>& knownResourceObjects,
766 SkTSet<SkPDFObject*>* newResourceObjects) {
767 GetResourcesHelper(&fResources, knownResourceObjects, newResourceObjects);
770 SkTypeface* SkPDFFont::typeface() {
771 return fTypeface.get();
774 SkAdvancedTypefaceMetrics::FontType SkPDFFont::getType() {
778 bool SkPDFFont::canEmbed() const {
779 if (!fFontInfo.get()) {
780 SkASSERT(fFontType == SkAdvancedTypefaceMetrics::kOther_Font);
783 return (fFontInfo->fFlags &
784 SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag) == 0;
787 bool SkPDFFont::canSubset() const {
788 if (!fFontInfo.get()) {
789 SkASSERT(fFontType == SkAdvancedTypefaceMetrics::kOther_Font);
792 return (fFontInfo->fFlags &
793 SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag) == 0;
796 bool SkPDFFont::hasGlyph(uint16_t id) {
797 return (id >= fFirstGlyphID && id <= fLastGlyphID) || id == 0;
800 int SkPDFFont::glyphsToPDFFontEncoding(uint16_t* glyphIDs, int numGlyphs) {
801 // A font with multibyte glyphs will support all glyph IDs in a single font.
802 if (this->multiByteGlyphs()) {
806 for (int i = 0; i < numGlyphs; i++) {
807 if (glyphIDs[i] == 0) {
810 if (glyphIDs[i] < fFirstGlyphID || glyphIDs[i] > fLastGlyphID) {
813 glyphIDs[i] -= (fFirstGlyphID - 1);
820 SkPDFFont* SkPDFFont::GetFontResource(SkTypeface* typeface, uint16_t glyphID) {
821 SkAutoMutexAcquire lock(CanonicalFontsMutex());
823 SkAutoResolveDefaultTypeface autoResolve(typeface);
824 typeface = autoResolve.get();
826 const uint32_t fontID = typeface->uniqueID();
827 int relatedFontIndex;
828 if (Find(fontID, glyphID, &relatedFontIndex)) {
829 CanonicalFonts()[relatedFontIndex].fFont->ref();
830 return CanonicalFonts()[relatedFontIndex].fFont;
833 SkAutoTUnref<const SkAdvancedTypefaceMetrics> fontMetrics;
834 SkPDFDict* relatedFontDescriptor = NULL;
835 if (relatedFontIndex >= 0) {
836 SkPDFFont* relatedFont = CanonicalFonts()[relatedFontIndex].fFont;
837 fontMetrics.reset(relatedFont->fontInfo());
838 SkSafeRef(fontMetrics.get());
839 relatedFontDescriptor = relatedFont->getFontDescriptor();
841 // This only is to catch callers who pass invalid glyph ids.
842 // If glyph id is invalid, then we will create duplicate entries
843 // for TrueType fonts.
844 SkAdvancedTypefaceMetrics::FontType fontType =
845 fontMetrics.get() ? fontMetrics.get()->fType :
846 SkAdvancedTypefaceMetrics::kOther_Font;
848 if (fontType == SkAdvancedTypefaceMetrics::kType1CID_Font ||
849 fontType == SkAdvancedTypefaceMetrics::kTrueType_Font) {
850 CanonicalFonts()[relatedFontIndex].fFont->ref();
851 return CanonicalFonts()[relatedFontIndex].fFont;
854 SkAdvancedTypefaceMetrics::PerGlyphInfo info;
855 info = SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo;
856 info = SkTBitOr<SkAdvancedTypefaceMetrics::PerGlyphInfo>(
857 info, SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo);
858 #if !defined (SK_SFNTLY_SUBSETTER)
859 info = SkTBitOr<SkAdvancedTypefaceMetrics::PerGlyphInfo>(
860 info, SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo);
863 typeface->getAdvancedTypefaceMetrics(info, NULL, 0));
864 #if defined (SK_SFNTLY_SUBSETTER)
865 if (fontMetrics.get() &&
866 fontMetrics->fType != SkAdvancedTypefaceMetrics::kTrueType_Font) {
867 // Font does not support subsetting, get new info with advance.
868 info = SkTBitOr<SkAdvancedTypefaceMetrics::PerGlyphInfo>(
869 info, SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo);
871 typeface->getAdvancedTypefaceMetrics(info, NULL, 0));
876 SkPDFFont* font = Create(fontMetrics.get(), typeface, glyphID,
877 relatedFontDescriptor);
878 FontRec newEntry(font, fontID, font->fFirstGlyphID);
879 CanonicalFonts().push(newEntry);
880 return font; // Return the reference new SkPDFFont() created.
883 SkPDFFont* SkPDFFont::getFontSubset(const SkPDFGlyphSet*) {
884 return NULL; // Default: no support.
888 SkTDArray<SkPDFFont::FontRec>& SkPDFFont::CanonicalFonts() {
889 SkPDFFont::CanonicalFontsMutex().assertHeld();
890 static SkTDArray<FontRec> gCanonicalFonts;
891 return gCanonicalFonts;
894 SK_DECLARE_STATIC_MUTEX(gCanonicalFontsMutex);
896 SkBaseMutex& SkPDFFont::CanonicalFontsMutex() {
897 return gCanonicalFontsMutex;
901 bool SkPDFFont::Find(uint32_t fontID, uint16_t glyphID, int* index) {
902 // TODO(vandebo): Optimize this, do only one search?
903 FontRec search(NULL, fontID, glyphID);
904 *index = CanonicalFonts().find(search);
909 *index = CanonicalFonts().find(search);
913 SkPDFFont::SkPDFFont(const SkAdvancedTypefaceMetrics* info,
914 SkTypeface* typeface,
915 SkPDFDict* relatedFontDescriptor)
917 fTypeface(ref_or_default(typeface)),
919 fLastGlyphID(info ? info->fLastGlyphID : 0),
920 fFontInfo(SkSafeRef(info)),
921 fDescriptor(SkSafeRef(relatedFontDescriptor)) {
923 info->fFlags & SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag) {
924 fFontType = SkAdvancedTypefaceMetrics::kOther_Font;
926 fFontType = info->fType;
931 SkPDFFont* SkPDFFont::Create(const SkAdvancedTypefaceMetrics* info,
932 SkTypeface* typeface, uint16_t glyphID,
933 SkPDFDict* relatedFontDescriptor) {
934 SkAdvancedTypefaceMetrics::FontType type =
935 info ? info->fType : SkAdvancedTypefaceMetrics::kOther_Font;
938 (info->fFlags & SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag)) {
939 NOT_IMPLEMENTED(true, true);
940 return new SkPDFType3Font(info,
944 if (type == SkAdvancedTypefaceMetrics::kType1CID_Font ||
945 type == SkAdvancedTypefaceMetrics::kTrueType_Font) {
946 SkASSERT(relatedFontDescriptor == NULL);
947 return new SkPDFType0Font(info, typeface);
949 if (type == SkAdvancedTypefaceMetrics::kType1_Font) {
950 return new SkPDFType1Font(info,
953 relatedFontDescriptor);
956 SkASSERT(type == SkAdvancedTypefaceMetrics::kCFF_Font ||
957 type == SkAdvancedTypefaceMetrics::kOther_Font);
959 return new SkPDFType3Font(info, typeface, glyphID);
962 const SkAdvancedTypefaceMetrics* SkPDFFont::fontInfo() {
963 return fFontInfo.get();
966 void SkPDFFont::setFontInfo(const SkAdvancedTypefaceMetrics* info) {
967 if (info == NULL || info == fFontInfo.get()) {
970 fFontInfo.reset(info);
974 uint16_t SkPDFFont::firstGlyphID() const {
975 return fFirstGlyphID;
978 uint16_t SkPDFFont::lastGlyphID() const {
982 void SkPDFFont::setLastGlyphID(uint16_t glyphID) {
983 fLastGlyphID = glyphID;
986 void SkPDFFont::addResource(SkPDFObject* object) {
987 SkASSERT(object != NULL);
988 fResources.push(object);
992 SkPDFDict* SkPDFFont::getFontDescriptor() {
993 return fDescriptor.get();
996 void SkPDFFont::setFontDescriptor(SkPDFDict* descriptor) {
997 fDescriptor.reset(descriptor);
998 SkSafeRef(descriptor);
1001 bool SkPDFFont::addCommonFontDescriptorEntries(int16_t defaultWidth) {
1002 if (fDescriptor.get() == NULL) {
1006 const uint16_t emSize = fFontInfo->fEmSize;
1008 fDescriptor->insertName("FontName", fFontInfo->fFontName);
1009 fDescriptor->insertInt("Flags", fFontInfo->fStyle | kPdfSymbolic);
1010 fDescriptor->insertScalar("Ascent",
1011 scaleFromFontUnits(fFontInfo->fAscent, emSize));
1012 fDescriptor->insertScalar("Descent",
1013 scaleFromFontUnits(fFontInfo->fDescent, emSize));
1014 fDescriptor->insertScalar("StemV",
1015 scaleFromFontUnits(fFontInfo->fStemV, emSize));
1017 fDescriptor->insertScalar("CapHeight",
1018 scaleFromFontUnits(fFontInfo->fCapHeight, emSize));
1019 fDescriptor->insertInt("ItalicAngle", fFontInfo->fItalicAngle);
1020 fDescriptor->insert("FontBBox", makeFontBBox(fFontInfo->fBBox,
1021 fFontInfo->fEmSize))->unref();
1023 if (defaultWidth > 0) {
1024 fDescriptor->insertScalar("MissingWidth",
1025 scaleFromFontUnits(defaultWidth, emSize));
1030 void SkPDFFont::adjustGlyphRangeForSingleByteEncoding(uint16_t glyphID) {
1031 // Single byte glyph encoding supports a max of 255 glyphs.
1032 fFirstGlyphID = glyphID - (glyphID - 1) % 255;
1033 if (fLastGlyphID > fFirstGlyphID + 255 - 1) {
1034 fLastGlyphID = fFirstGlyphID + 255 - 1;
1038 bool SkPDFFont::FontRec::operator==(const SkPDFFont::FontRec& b) const {
1039 if (fFontID != b.fFontID) {
1042 if (fFont != NULL && b.fFont != NULL) {
1043 return fFont->fFirstGlyphID == b.fFont->fFirstGlyphID &&
1044 fFont->fLastGlyphID == b.fFont->fLastGlyphID;
1046 if (fGlyphID == 0 || b.fGlyphID == 0) {
1050 if (fFont != NULL) {
1051 return fFont->fFirstGlyphID <= b.fGlyphID &&
1052 b.fGlyphID <= fFont->fLastGlyphID;
1053 } else if (b.fFont != NULL) {
1054 return b.fFont->fFirstGlyphID <= fGlyphID &&
1055 fGlyphID <= b.fFont->fLastGlyphID;
1057 return fGlyphID == b.fGlyphID;
1060 SkPDFFont::FontRec::FontRec(SkPDFFont* font, uint32_t fontID, uint16_t glyphID)
1066 void SkPDFFont::populateToUnicodeTable(const SkPDFGlyphSet* subset) {
1067 if (fFontInfo == NULL || fFontInfo->fGlyphToUnicode.begin() == NULL) {
1070 SkAutoTUnref<SkPDFStream> pdfCmap(
1071 generate_tounicode_cmap(fFontInfo->fGlyphToUnicode, subset,
1072 multiByteGlyphs(), firstGlyphID(),
1074 addResource(pdfCmap.get());
1075 insert("ToUnicode", new SkPDFObjRef(pdfCmap.get()))->unref();
1078 ///////////////////////////////////////////////////////////////////////////////
1079 // class SkPDFType0Font
1080 ///////////////////////////////////////////////////////////////////////////////
1082 SkPDFType0Font::SkPDFType0Font(const SkAdvancedTypefaceMetrics* info,
1083 SkTypeface* typeface)
1084 : SkPDFFont(info, typeface, NULL) {
1085 SkDEBUGCODE(fPopulated = false);
1091 SkPDFType0Font::~SkPDFType0Font() {}
1093 SkPDFFont* SkPDFType0Font::getFontSubset(const SkPDFGlyphSet* subset) {
1097 SkPDFType0Font* newSubset = new SkPDFType0Font(fontInfo(), typeface());
1098 newSubset->populate(subset);
1103 void SkPDFType0Font::emitObject(SkWStream* stream, SkPDFCatalog* catalog,
1105 SkASSERT(fPopulated);
1106 return INHERITED::emitObject(stream, catalog, indirect);
1110 bool SkPDFType0Font::populate(const SkPDFGlyphSet* subset) {
1111 insertName("Subtype", "Type0");
1112 insertName("BaseFont", fontInfo()->fFontName);
1113 insertName("Encoding", "Identity-H");
1115 SkAutoTUnref<SkPDFCIDFont> newCIDFont(
1116 new SkPDFCIDFont(fontInfo(), typeface(), subset));
1117 addResource(newCIDFont.get());
1118 SkAutoTUnref<SkPDFArray> descendantFonts(new SkPDFArray());
1119 descendantFonts->append(new SkPDFObjRef(newCIDFont.get()))->unref();
1120 insert("DescendantFonts", descendantFonts.get());
1122 populateToUnicodeTable(subset);
1124 SkDEBUGCODE(fPopulated = true);
1128 ///////////////////////////////////////////////////////////////////////////////
1129 // class SkPDFCIDFont
1130 ///////////////////////////////////////////////////////////////////////////////
1132 SkPDFCIDFont::SkPDFCIDFont(const SkAdvancedTypefaceMetrics* info,
1133 SkTypeface* typeface, const SkPDFGlyphSet* subset)
1134 : SkPDFFont(info, typeface, NULL) {
1138 SkPDFCIDFont::~SkPDFCIDFont() {}
1140 bool SkPDFCIDFont::addFontDescriptor(int16_t defaultWidth,
1141 const SkTDArray<uint32_t>* subset) {
1142 SkAutoTUnref<SkPDFDict> descriptor(new SkPDFDict("FontDescriptor"));
1143 setFontDescriptor(descriptor.get());
1144 addResource(descriptor.get());
1145 insert("FontDescriptor", new SkPDFObjRef(descriptor.get()))->unref();
1146 if (!addCommonFontDescriptorEntries(defaultWidth)) {
1153 switch (getType()) {
1154 case SkAdvancedTypefaceMetrics::kTrueType_Font: {
1155 SkAutoTUnref<SkPDFStream> fontStream;
1156 size_t fontSize = 0;
1158 SkPDFStream* rawStream = NULL;
1159 fontSize = get_subset_font_stream(fontInfo()->fFontName.c_str(),
1163 fontStream.reset(rawStream);
1166 SkAutoTUnref<SkStream> fontData(
1167 typeface()->openStream(&ttcIndex));
1168 fontStream.reset(new SkPDFStream(fontData.get()));
1169 fontSize = fontData->getLength();
1172 SkASSERT(fontStream.get());
1173 addResource(fontStream.get());
1175 fontStream->insertInt("Length1", fontSize);
1176 descriptor->insert("FontFile2",
1177 new SkPDFObjRef(fontStream.get()))->unref();
1180 case SkAdvancedTypefaceMetrics::kCFF_Font:
1181 case SkAdvancedTypefaceMetrics::kType1CID_Font: {
1183 SkAutoTUnref<SkStream> fontData(typeface()->openStream(&ttcIndex));
1184 SkAutoTUnref<SkPDFStream> fontStream(
1185 new SkPDFStream(fontData.get()));
1186 addResource(fontStream.get());
1188 if (getType() == SkAdvancedTypefaceMetrics::kCFF_Font) {
1189 fontStream->insertName("Subtype", "Type1C");
1191 fontStream->insertName("Subtype", "CIDFontType0c");
1193 descriptor->insert("FontFile3",
1194 new SkPDFObjRef(fontStream.get()))->unref();
1203 bool SkPDFCIDFont::populate(const SkPDFGlyphSet* subset) {
1204 // Generate new font metrics with advance info for true type fonts.
1205 if (fontInfo()->fType == SkAdvancedTypefaceMetrics::kTrueType_Font) {
1206 // Generate glyph id array.
1207 SkTDArray<uint32_t> glyphIDs;
1209 // Always include glyph 0.
1210 if (!subset->has(0)) {
1213 subset->exportTo(&glyphIDs);
1216 SkAdvancedTypefaceMetrics::PerGlyphInfo info;
1217 info = SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo;
1218 info = SkTBitOr<SkAdvancedTypefaceMetrics::PerGlyphInfo>(
1219 info, SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo);
1220 uint32_t* glyphs = (glyphIDs.count() == 0) ? NULL : glyphIDs.begin();
1221 uint32_t glyphsCount = glyphs ? glyphIDs.count() : 0;
1222 SkAutoTUnref<const SkAdvancedTypefaceMetrics> fontMetrics(
1223 typeface()->getAdvancedTypefaceMetrics(info, glyphs, glyphsCount));
1224 setFontInfo(fontMetrics.get());
1225 addFontDescriptor(0, &glyphIDs);
1228 addFontDescriptor(0, NULL);
1231 insertName("BaseFont", fontInfo()->fFontName);
1233 if (getType() == SkAdvancedTypefaceMetrics::kType1CID_Font) {
1234 insertName("Subtype", "CIDFontType0");
1235 } else if (getType() == SkAdvancedTypefaceMetrics::kTrueType_Font) {
1236 insertName("Subtype", "CIDFontType2");
1237 insertName("CIDToGIDMap", "Identity");
1242 SkAutoTUnref<SkPDFDict> sysInfo(new SkPDFDict);
1243 sysInfo->insert("Registry", new SkPDFString("Adobe"))->unref();
1244 sysInfo->insert("Ordering", new SkPDFString("Identity"))->unref();
1245 sysInfo->insertInt("Supplement", 0);
1246 insert("CIDSystemInfo", sysInfo.get());
1248 if (fontInfo()->fGlyphWidths.get()) {
1249 int16_t defaultWidth = 0;
1250 SkAutoTUnref<SkPDFArray> widths(
1251 composeAdvanceData(fontInfo()->fGlyphWidths.get(),
1252 fontInfo()->fEmSize, &appendWidth,
1255 insert("W", widths.get());
1256 if (defaultWidth != 0) {
1257 insertScalar("DW", scaleFromFontUnits(defaultWidth,
1258 fontInfo()->fEmSize));
1261 if (fontInfo()->fVerticalMetrics.get()) {
1262 struct SkAdvancedTypefaceMetrics::VerticalMetric defaultAdvance;
1263 defaultAdvance.fVerticalAdvance = 0;
1264 defaultAdvance.fOriginXDisp = 0;
1265 defaultAdvance.fOriginYDisp = 0;
1266 SkAutoTUnref<SkPDFArray> advances(
1267 composeAdvanceData(fontInfo()->fVerticalMetrics.get(),
1268 fontInfo()->fEmSize, &appendVerticalAdvance,
1270 if (advances->size())
1271 insert("W2", advances.get());
1272 if (defaultAdvance.fVerticalAdvance ||
1273 defaultAdvance.fOriginXDisp ||
1274 defaultAdvance.fOriginYDisp) {
1275 insert("DW2", appendVerticalAdvance(defaultAdvance,
1276 fontInfo()->fEmSize,
1277 new SkPDFArray))->unref();
1284 ///////////////////////////////////////////////////////////////////////////////
1285 // class SkPDFType1Font
1286 ///////////////////////////////////////////////////////////////////////////////
1288 SkPDFType1Font::SkPDFType1Font(const SkAdvancedTypefaceMetrics* info,
1289 SkTypeface* typeface,
1291 SkPDFDict* relatedFontDescriptor)
1292 : SkPDFFont(info, typeface, relatedFontDescriptor) {
1296 SkPDFType1Font::~SkPDFType1Font() {}
1298 bool SkPDFType1Font::addFontDescriptor(int16_t defaultWidth) {
1299 if (getFontDescriptor() != NULL) {
1300 SkPDFDict* descriptor = getFontDescriptor();
1301 addResource(descriptor);
1302 insert("FontDescriptor", new SkPDFObjRef(descriptor))->unref();
1306 SkAutoTUnref<SkPDFDict> descriptor(new SkPDFDict("FontDescriptor"));
1307 setFontDescriptor(descriptor.get());
1310 size_t header SK_INIT_TO_AVOID_WARNING;
1311 size_t data SK_INIT_TO_AVOID_WARNING;
1312 size_t trailer SK_INIT_TO_AVOID_WARNING;
1313 SkAutoTUnref<SkStream> rawFontData(typeface()->openStream(&ttcIndex));
1314 SkAutoTUnref<SkData> fontData(handle_type1_stream(rawFontData.get(), &header,
1316 if (fontData.get() == NULL) {
1320 SkAutoTUnref<SkPDFStream> fontStream(new SkPDFStream(fontData.get()));
1321 addResource(fontStream.get());
1322 fontStream->insertInt("Length1", header);
1323 fontStream->insertInt("Length2", data);
1324 fontStream->insertInt("Length3", trailer);
1325 descriptor->insert("FontFile",
1326 new SkPDFObjRef(fontStream.get()))->unref();
1329 addResource(descriptor.get());
1330 insert("FontDescriptor", new SkPDFObjRef(descriptor.get()))->unref();
1332 return addCommonFontDescriptorEntries(defaultWidth);
1335 bool SkPDFType1Font::populate(int16_t glyphID) {
1336 SkASSERT(!fontInfo()->fVerticalMetrics.get());
1337 SkASSERT(fontInfo()->fGlyphWidths.get());
1339 adjustGlyphRangeForSingleByteEncoding(glyphID);
1341 int16_t defaultWidth = 0;
1342 const SkAdvancedTypefaceMetrics::WidthRange* widthRangeEntry = NULL;
1343 const SkAdvancedTypefaceMetrics::WidthRange* widthEntry;
1344 for (widthEntry = fontInfo()->fGlyphWidths.get();
1346 widthEntry = widthEntry->fNext.get()) {
1347 switch (widthEntry->fType) {
1348 case SkAdvancedTypefaceMetrics::WidthRange::kDefault:
1349 defaultWidth = widthEntry->fAdvance[0];
1351 case SkAdvancedTypefaceMetrics::WidthRange::kRun:
1354 case SkAdvancedTypefaceMetrics::WidthRange::kRange:
1355 SkASSERT(widthRangeEntry == NULL);
1356 widthRangeEntry = widthEntry;
1361 if (!addFontDescriptor(defaultWidth)) {
1365 insertName("Subtype", "Type1");
1366 insertName("BaseFont", fontInfo()->fFontName);
1368 addWidthInfoFromRange(defaultWidth, widthRangeEntry);
1370 SkAutoTUnref<SkPDFDict> encoding(new SkPDFDict("Encoding"));
1371 insert("Encoding", encoding.get());
1373 SkAutoTUnref<SkPDFArray> encDiffs(new SkPDFArray);
1374 encoding->insert("Differences", encDiffs.get());
1376 encDiffs->reserve(lastGlyphID() - firstGlyphID() + 2);
1377 encDiffs->appendInt(1);
1378 for (int gID = firstGlyphID(); gID <= lastGlyphID(); gID++) {
1379 encDiffs->appendName(fontInfo()->fGlyphNames->get()[gID].c_str());
1385 void SkPDFType1Font::addWidthInfoFromRange(
1386 int16_t defaultWidth,
1387 const SkAdvancedTypefaceMetrics::WidthRange* widthRangeEntry) {
1388 SkAutoTUnref<SkPDFArray> widthArray(new SkPDFArray());
1390 if (widthRangeEntry) {
1391 const uint16_t emSize = fontInfo()->fEmSize;
1392 int startIndex = firstGlyphID() - widthRangeEntry->fStartId;
1393 int endIndex = startIndex + lastGlyphID() - firstGlyphID() + 1;
1396 if (endIndex > widthRangeEntry->fAdvance.count())
1397 endIndex = widthRangeEntry->fAdvance.count();
1398 if (widthRangeEntry->fStartId == 0) {
1399 appendWidth(widthRangeEntry->fAdvance[0], emSize, widthArray.get());
1401 firstChar = startIndex + widthRangeEntry->fStartId;
1403 for (int i = startIndex; i < endIndex; i++) {
1404 appendWidth(widthRangeEntry->fAdvance[i], emSize, widthArray.get());
1407 appendWidth(defaultWidth, 1000, widthArray.get());
1409 insertInt("FirstChar", firstChar);
1410 insertInt("LastChar", firstChar + widthArray->size() - 1);
1411 insert("Widths", widthArray.get());
1414 ///////////////////////////////////////////////////////////////////////////////
1415 // class SkPDFType3Font
1416 ///////////////////////////////////////////////////////////////////////////////
1418 SkPDFType3Font::SkPDFType3Font(const SkAdvancedTypefaceMetrics* info,
1419 SkTypeface* typeface,
1421 : SkPDFFont(info, typeface, NULL) {
1425 SkPDFType3Font::~SkPDFType3Font() {}
1427 bool SkPDFType3Font::populate(uint16_t glyphID) {
1429 paint.setTypeface(typeface());
1430 paint.setTextSize(1000);
1431 SkAutoGlyphCache autoCache(paint, NULL, NULL);
1432 SkGlyphCache* cache = autoCache.getCache();
1433 // If fLastGlyphID isn't set (because there is not fFontInfo), look it up.
1434 if (lastGlyphID() == 0) {
1435 setLastGlyphID(cache->getGlyphCount() - 1);
1438 adjustGlyphRangeForSingleByteEncoding(glyphID);
1440 insertName("Subtype", "Type3");
1441 // Flip about the x-axis and scale by 1/1000.
1442 SkMatrix fontMatrix;
1443 fontMatrix.setScale(SkScalarInvert(1000), -SkScalarInvert(1000));
1444 insert("FontMatrix", SkPDFUtils::MatrixToArray(fontMatrix))->unref();
1446 SkAutoTUnref<SkPDFDict> charProcs(new SkPDFDict);
1447 insert("CharProcs", charProcs.get());
1449 SkAutoTUnref<SkPDFDict> encoding(new SkPDFDict("Encoding"));
1450 insert("Encoding", encoding.get());
1452 SkAutoTUnref<SkPDFArray> encDiffs(new SkPDFArray);
1453 encoding->insert("Differences", encDiffs.get());
1454 encDiffs->reserve(lastGlyphID() - firstGlyphID() + 2);
1455 encDiffs->appendInt(1);
1457 SkAutoTUnref<SkPDFArray> widthArray(new SkPDFArray());
1459 SkIRect bbox = SkIRect::MakeEmpty();
1460 for (int gID = firstGlyphID(); gID <= lastGlyphID(); gID++) {
1461 SkString characterName;
1462 characterName.printf("gid%d", gID);
1463 encDiffs->appendName(characterName.c_str());
1465 const SkGlyph& glyph = cache->getGlyphIDMetrics(gID);
1466 widthArray->appendScalar(SkFixedToScalar(glyph.fAdvanceX));
1467 SkIRect glyphBBox = SkIRect::MakeXYWH(glyph.fLeft, glyph.fTop,
1468 glyph.fWidth, glyph.fHeight);
1469 bbox.join(glyphBBox);
1471 SkDynamicMemoryWStream content;
1472 setGlyphWidthAndBoundingBox(SkFixedToScalar(glyph.fAdvanceX), glyphBBox,
1474 const SkPath* path = cache->findPath(glyph);
1476 SkPDFUtils::EmitPath(*path, paint.getStyle(), &content);
1477 SkPDFUtils::PaintPath(paint.getStyle(), path->getFillType(),
1480 SkAutoTUnref<SkMemoryStream> glyphStream(new SkMemoryStream());
1481 glyphStream->setData(content.copyToData())->unref();
1483 SkAutoTUnref<SkPDFStream> glyphDescription(
1484 new SkPDFStream(glyphStream.get()));
1485 addResource(glyphDescription.get());
1486 charProcs->insert(characterName.c_str(),
1487 new SkPDFObjRef(glyphDescription.get()))->unref();
1490 insert("FontBBox", makeFontBBox(bbox, 1000))->unref();
1491 insertInt("FirstChar", 1);
1492 insertInt("LastChar", lastGlyphID() - firstGlyphID() + 1);
1493 insert("Widths", widthArray.get());
1494 insertName("CIDToGIDMap", "Identity");
1496 populateToUnicodeTable(NULL);