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