blob: 1333c9f6c73b27532974896d1ed28905f150e3ed [file] [log] [blame]
epoger@google.comec3ed6a2011-07-28 14:26:00 +00001
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00003 * Copyright 2011 Google Inc.
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00004 *
epoger@google.comec3ed6a2011-07-28 14:26:00 +00005 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00007 */
8
epoger@google.comec3ed6a2011-07-28 14:26:00 +00009
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000010#include <ctype.h>
11
reed@google.com8a85d0c2011-06-24 19:12:12 +000012#include "SkData.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000013#include "SkFontHost.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000014#include "SkGlyphCache.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000015#include "SkPaint.h"
vandebo@chromium.org98594282011-07-25 22:34:12 +000016#include "SkPDFCatalog.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000017#include "SkPDFDevice.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000018#include "SkPDFFont.h"
vandebo@chromium.org98594282011-07-25 22:34:12 +000019#include "SkPDFFontImpl.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000020#include "SkPDFStream.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000021#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000022#include "SkPDFUtils.h"
vandebo@chromium.orgf77e27d2011-03-10 22:50:28 +000023#include "SkRefCnt.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000024#include "SkScalar.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000025#include "SkStream.h"
26#include "SkTypeface.h"
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +000027#include "SkTypes.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000028#include "SkUtils.h"
29
vandebo@chromium.org1f165892011-07-26 02:11:41 +000030#if defined (SK_SFNTLY_SUBSETTER)
31#include SK_SFNTLY_SUBSETTER
32#endif
33
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000034namespace {
35
vandebo@chromium.org98594282011-07-25 22:34:12 +000036///////////////////////////////////////////////////////////////////////////////
37// File-Local Functions
38///////////////////////////////////////////////////////////////////////////////
39
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000040bool parsePFBSection(const uint8_t** src, size_t* len, int sectionType,
41 size_t* size) {
42 // PFB sections have a two or six bytes header. 0x80 and a one byte
43 // section type followed by a four byte section length. Type one is
44 // an ASCII section (includes a length), type two is a binary section
45 // (includes a length) and type three is an EOF marker with no length.
46 const uint8_t* buf = *src;
47 if (*len < 2 || buf[0] != 0x80 || buf[1] != sectionType)
48 return false;
49 if (buf[1] == 3)
50 return true;
51 if (*len < 6)
52 return false;
53
vandebo@chromium.org73322072011-06-21 21:19:41 +000054 *size = (size_t)buf[2] | ((size_t)buf[3] << 8) | ((size_t)buf[4] << 16) |
55 ((size_t)buf[5] << 24);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000056 size_t consumed = *size + 6;
57 if (consumed > *len)
58 return false;
59 *src = *src + consumed;
60 *len = *len - consumed;
61 return true;
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000062}
63
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000064bool parsePFB(const uint8_t* src, size_t size, size_t* headerLen,
65 size_t* dataLen, size_t* trailerLen) {
66 const uint8_t* srcPtr = src;
67 size_t remaining = size;
68
69 return parsePFBSection(&srcPtr, &remaining, 1, headerLen) &&
70 parsePFBSection(&srcPtr, &remaining, 2, dataLen) &&
71 parsePFBSection(&srcPtr, &remaining, 1, trailerLen) &&
72 parsePFBSection(&srcPtr, &remaining, 3, NULL);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000073}
74
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000075/* The sections of a PFA file are implicitly defined. The body starts
76 * after the line containing "eexec," and the trailer starts with 512
77 * literal 0's followed by "cleartomark" (plus arbitrary white space).
78 *
79 * This function assumes that src is NUL terminated, but the NUL
80 * termination is not included in size.
81 *
82 */
83bool parsePFA(const char* src, size_t size, size_t* headerLen,
84 size_t* hexDataLen, size_t* dataLen, size_t* trailerLen) {
85 const char* end = src + size;
86
87 const char* dataPos = strstr(src, "eexec");
88 if (!dataPos)
89 return false;
90 dataPos += strlen("eexec");
91 while ((*dataPos == '\n' || *dataPos == '\r' || *dataPos == ' ') &&
92 dataPos < end)
93 dataPos++;
94 *headerLen = dataPos - src;
95
96 const char* trailerPos = strstr(dataPos, "cleartomark");
97 if (!trailerPos)
98 return false;
99 int zeroCount = 0;
100 for (trailerPos--; trailerPos > dataPos && zeroCount < 512; trailerPos--) {
101 if (*trailerPos == '\n' || *trailerPos == '\r' || *trailerPos == ' ') {
102 continue;
103 } else if (*trailerPos == '0') {
104 zeroCount++;
105 } else {
106 return false;
107 }
108 }
109 if (zeroCount != 512)
110 return false;
111
112 *hexDataLen = trailerPos - src - *headerLen;
113 *trailerLen = size - *headerLen - *hexDataLen;
114
115 // Verify that the data section is hex encoded and count the bytes.
116 int nibbles = 0;
117 for (; dataPos < trailerPos; dataPos++) {
118 if (isspace(*dataPos))
119 continue;
120 if (!isxdigit(*dataPos))
121 return false;
122 nibbles++;
123 }
124 *dataLen = (nibbles + 1) / 2;
125
126 return true;
127}
128
129int8_t hexToBin(uint8_t c) {
130 if (!isxdigit(c))
131 return -1;
132 if (c <= '9') return c - '0';
133 if (c <= 'F') return c - 'A' + 10;
134 if (c <= 'f') return c - 'a' + 10;
135 return -1;
136}
137
138SkStream* handleType1Stream(SkStream* srcStream, size_t* headerLen,
139 size_t* dataLen, size_t* trailerLen) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000140 // srcStream may be backed by a file or a unseekable fd, so we may not be
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000141 // able to use skip(), rewind(), or getMemoryBase(). read()ing through
142 // the input only once is doable, but very ugly. Furthermore, it'd be nice
143 // if the data was NUL terminated so that we can use strstr() to search it.
144 // Make as few copies as possible given these constraints.
145 SkDynamicMemoryWStream dynamicStream;
146 SkRefPtr<SkMemoryStream> staticStream;
reed@google.com8a85d0c2011-06-24 19:12:12 +0000147 SkData* data = NULL;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000148 const uint8_t* src;
149 size_t srcLen;
150 if ((srcLen = srcStream->getLength()) > 0) {
151 staticStream = new SkMemoryStream(srcLen + 1);
152 staticStream->unref(); // new and SkRefPtr both took a ref.
153 src = (const uint8_t*)staticStream->getMemoryBase();
154 if (srcStream->getMemoryBase() != NULL) {
155 memcpy((void *)src, srcStream->getMemoryBase(), srcLen);
156 } else {
157 size_t read = 0;
158 while (read < srcLen) {
159 size_t got = srcStream->read((void *)staticStream->getAtPos(),
160 srcLen - read);
161 if (got == 0)
162 return NULL;
163 read += got;
164 staticStream->seek(read);
165 }
166 }
167 ((uint8_t *)src)[srcLen] = 0;
168 } else {
169 static const size_t bufSize = 4096;
170 uint8_t buf[bufSize];
171 size_t amount;
172 while ((amount = srcStream->read(buf, bufSize)) > 0)
173 dynamicStream.write(buf, amount);
174 amount = 0;
175 dynamicStream.write(&amount, 1); // NULL terminator.
reed@google.com8a85d0c2011-06-24 19:12:12 +0000176 data = dynamicStream.copyToData();
177 src = data->bytes();
178 srcLen = data->size() - 1;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000179 }
180
reed@google.com8a85d0c2011-06-24 19:12:12 +0000181 // this handles releasing the data we may have gotten from dynamicStream.
182 // if data is null, it is a no-op
183 SkAutoDataUnref aud(data);
184
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000185 if (parsePFB(src, srcLen, headerLen, dataLen, trailerLen)) {
186 SkMemoryStream* result =
187 new SkMemoryStream(*headerLen + *dataLen + *trailerLen);
188 memcpy((char*)result->getAtPos(), src + 6, *headerLen);
189 result->seek(*headerLen);
190 memcpy((char*)result->getAtPos(), src + 6 + *headerLen + 6, *dataLen);
191 result->seek(*headerLen + *dataLen);
192 memcpy((char*)result->getAtPos(), src + 6 + *headerLen + 6 + *dataLen,
193 *trailerLen);
194 result->rewind();
195 return result;
196 }
197
198 // A PFA has to be converted for PDF.
199 size_t hexDataLen;
200 if (parsePFA((const char*)src, srcLen, headerLen, &hexDataLen, dataLen,
201 trailerLen)) {
202 SkMemoryStream* result =
203 new SkMemoryStream(*headerLen + *dataLen + *trailerLen);
204 memcpy((char*)result->getAtPos(), src, *headerLen);
205 result->seek(*headerLen);
206
207 const uint8_t* hexData = src + *headerLen;
208 const uint8_t* trailer = hexData + hexDataLen;
209 size_t outputOffset = 0;
vandebo@chromium.org5b073682011-03-08 18:33:31 +0000210 uint8_t dataByte = 0; // To hush compiler.
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000211 bool highNibble = true;
212 for (; hexData < trailer; hexData++) {
213 char curNibble = hexToBin(*hexData);
214 if (curNibble < 0)
215 continue;
216 if (highNibble) {
217 dataByte = curNibble << 4;
218 highNibble = false;
219 } else {
220 dataByte |= curNibble;
221 highNibble = true;
222 ((char *)result->getAtPos())[outputOffset++] = dataByte;
223 }
224 }
225 if (!highNibble)
226 ((char *)result->getAtPos())[outputOffset++] = dataByte;
227 SkASSERT(outputOffset == *dataLen);
228 result->seek(*headerLen + outputOffset);
229
230 memcpy((char *)result->getAtPos(), src + *headerLen + hexDataLen,
231 *trailerLen);
232 result->rewind();
233 return result;
234 }
235
236 return NULL;
237}
238
reed@google.com3f0dcf92011-03-18 21:23:45 +0000239// scale from em-units to base-1000, returning as a SkScalar
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000240SkScalar scaleFromFontUnits(int16_t val, uint16_t emSize) {
reed@google.com3f0dcf92011-03-18 21:23:45 +0000241 SkScalar scaled = SkIntToScalar(val);
242 if (emSize == 1000) {
243 return scaled;
244 } else {
245 return SkScalarMulDiv(scaled, 1000, emSize);
246 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000247}
248
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000249void setGlyphWidthAndBoundingBox(SkScalar width, SkIRect box,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000250 SkWStream* content) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000251 // Specify width and bounding box for the glyph.
252 SkPDFScalar::Append(width, content);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000253 content->writeText(" 0 ");
254 content->writeDecAsText(box.fLeft);
255 content->writeText(" ");
256 content->writeDecAsText(box.fTop);
257 content->writeText(" ");
258 content->writeDecAsText(box.fRight);
259 content->writeText(" ");
260 content->writeDecAsText(box.fBottom);
261 content->writeText(" d1\n");
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000262}
263
vandebo@chromium.org75f97e42011-04-11 23:24:18 +0000264SkPDFArray* makeFontBBox(SkIRect glyphBBox, uint16_t emSize) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000265 SkPDFArray* bbox = new SkPDFArray;
266 bbox->reserve(4);
reed@google.comc789cf12011-07-20 12:14:33 +0000267 bbox->appendScalar(scaleFromFontUnits(glyphBBox.fLeft, emSize));
268 bbox->appendScalar(scaleFromFontUnits(glyphBBox.fBottom, emSize));
269 bbox->appendScalar(scaleFromFontUnits(glyphBBox.fRight, emSize));
270 bbox->appendScalar(scaleFromFontUnits(glyphBBox.fTop, emSize));
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000271 return bbox;
272}
273
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000274SkPDFArray* appendWidth(const int16_t& width, uint16_t emSize,
275 SkPDFArray* array) {
reed@google.comc789cf12011-07-20 12:14:33 +0000276 array->appendScalar(scaleFromFontUnits(width, emSize));
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +0000277 return array;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000278}
279
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +0000280SkPDFArray* appendVerticalAdvance(
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000281 const SkAdvancedTypefaceMetrics::VerticalMetric& advance,
282 uint16_t emSize, SkPDFArray* array) {
283 appendWidth(advance.fVerticalAdvance, emSize, array);
284 appendWidth(advance.fOriginXDisp, emSize, array);
285 appendWidth(advance.fOriginYDisp, emSize, array);
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +0000286 return array;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000287}
288
289template <typename Data>
290SkPDFArray* composeAdvanceData(
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000291 SkAdvancedTypefaceMetrics::AdvanceMetric<Data>* advanceInfo,
292 uint16_t emSize,
293 SkPDFArray* (*appendAdvance)(const Data& advance, uint16_t emSize,
294 SkPDFArray* array),
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000295 Data* defaultAdvance) {
296 SkPDFArray* result = new SkPDFArray();
297 for (; advanceInfo != NULL; advanceInfo = advanceInfo->fNext.get()) {
298 switch (advanceInfo->fType) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000299 case SkAdvancedTypefaceMetrics::WidthRange::kDefault: {
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000300 SkASSERT(advanceInfo->fAdvance.count() == 1);
301 *defaultAdvance = advanceInfo->fAdvance[0];
302 break;
303 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000304 case SkAdvancedTypefaceMetrics::WidthRange::kRange: {
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000305 SkRefPtr<SkPDFArray> advanceArray = new SkPDFArray();
306 advanceArray->unref(); // SkRefPtr and new both took a ref.
307 for (int j = 0; j < advanceInfo->fAdvance.count(); j++)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000308 appendAdvance(advanceInfo->fAdvance[j], emSize,
309 advanceArray.get());
reed@google.comc789cf12011-07-20 12:14:33 +0000310 result->appendInt(advanceInfo->fStartId);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000311 result->append(advanceArray.get());
312 break;
313 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000314 case SkAdvancedTypefaceMetrics::WidthRange::kRun: {
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000315 SkASSERT(advanceInfo->fAdvance.count() == 1);
reed@google.comc789cf12011-07-20 12:14:33 +0000316 result->appendInt(advanceInfo->fStartId);
317 result->appendInt(advanceInfo->fEndId);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000318 appendAdvance(advanceInfo->fAdvance[0], emSize, result);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000319 break;
320 }
321 }
322 }
323 return result;
324}
325
326} // namespace
327
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000328static void append_tounicode_header(SkDynamicMemoryWStream* cmap) {
329 // 12 dict begin: 12 is an Adobe-suggested value. Shall not change.
330 // It's there to prevent old version Adobe Readers from malfunctioning.
331 const char* kHeader =
332 "/CIDInit /ProcSet findresource begin\n"
333 "12 dict begin\n"
334 "begincmap\n";
335 cmap->writeText(kHeader);
336
337 // The /CIDSystemInfo must be consistent to the one in
338 // SkPDFFont::populateCIDFont().
339 // We can not pass over the system info object here because the format is
340 // different. This is not a reference object.
341 const char* kSysInfo =
342 "/CIDSystemInfo\n"
343 "<< /Registry (Adobe)\n"
344 "/Ordering (UCS)\n"
345 "/Supplement 0\n"
346 ">> def\n";
347 cmap->writeText(kSysInfo);
348
349 // The CMapName must be consistent to /CIDSystemInfo above.
350 // /CMapType 2 means ToUnicode.
351 // We specify codespacerange from 0x0000 to 0xFFFF because we convert our
352 // code table from unsigned short (16-bits). Codespace range just tells the
353 // PDF processor the valid range. It does not matter whether a complete
354 // mapping is provided or not.
355 const char* kTypeInfo =
356 "/CMapName /Adobe-Identity-UCS def\n"
357 "/CMapType 2 def\n"
358 "1 begincodespacerange\n"
359 "<0000> <FFFF>\n"
360 "endcodespacerange\n";
361 cmap->writeText(kTypeInfo);
362}
363
364static void append_cmap_bfchar_table(uint16_t* glyph_id, SkUnichar* unicode,
365 size_t count,
366 SkDynamicMemoryWStream* cmap) {
367 cmap->writeDecAsText(count);
368 cmap->writeText(" beginbfchar\n");
369 for (size_t i = 0; i < count; ++i) {
370 cmap->writeText("<");
371 cmap->writeHexAsText(glyph_id[i], 4);
372 cmap->writeText("> <");
373 cmap->writeHexAsText(unicode[i], 4);
374 cmap->writeText(">\n");
375 }
376 cmap->writeText("endbfchar\n");
377}
378
379static void append_cmap_footer(SkDynamicMemoryWStream* cmap) {
380 const char* kFooter =
381 "endcmap\n"
382 "CMapName currentdict /CMap defineresource pop\n"
383 "end\n"
384 "end";
385 cmap->writeText(kFooter);
386}
387
388// Generate <bfchar> table according to PDF spec 1.4 and Adobe Technote 5014.
389static void append_cmap_bfchar_sections(
390 const SkTDArray<SkUnichar>& glyphUnicode,
vandebo@chromium.org98594282011-07-25 22:34:12 +0000391 const SkPDFGlyphSet* subset, SkDynamicMemoryWStream* cmap) {
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000392 // PDF spec defines that every bf* list can have at most 100 entries.
393 const size_t kMaxEntries = 100;
394 uint16_t glyphId[kMaxEntries];
395 SkUnichar unicode[kMaxEntries];
396 size_t index = 0;
397 for (int i = 0; i < glyphUnicode.count(); i++) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000398 if (glyphUnicode[i] && (subset == NULL || subset->has(i))) {
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000399 glyphId[index] = i;
400 unicode[index] = glyphUnicode[i];
401 ++index;
402 }
403 if (index == kMaxEntries) {
404 append_cmap_bfchar_table(glyphId, unicode, index, cmap);
405 index = 0;
406 }
407 }
408
409 if (index) {
410 append_cmap_bfchar_table(glyphId, unicode, index, cmap);
411 }
412}
413
vandebo@chromium.org98594282011-07-25 22:34:12 +0000414static SkPDFStream* generate_tounicode_cmap(
415 const SkTDArray<SkUnichar>& glyphUnicode,
416 const SkPDFGlyphSet* subset) {
417 SkDynamicMemoryWStream cmap;
418 append_tounicode_header(&cmap);
419 append_cmap_bfchar_sections(glyphUnicode, subset, &cmap);
420 append_cmap_footer(&cmap);
421 SkRefPtr<SkMemoryStream> cmapStream = new SkMemoryStream();
422 cmapStream->unref(); // SkRefPtr and new took a reference.
423 cmapStream->setData(cmap.copyToData());
424 return new SkPDFStream(cmapStream.get());
425}
426
vandebo@chromium.org1f165892011-07-26 02:11:41 +0000427static void sk_delete_array(const void* ptr, size_t, void*) {
428 // Use C-style cast to cast away const and cast type simultaneously.
429 delete[] (unsigned char*)ptr;
430}
431
432static int get_subset_font_stream(const char* fontName,
433 const SkTypeface* typeface,
434 const SkPDFGlyphSet* subset,
435 SkPDFStream** fontStream) {
436 SkRefPtr<SkStream> fontData =
437 SkFontHost::OpenStream(SkTypeface::UniqueID(typeface));
438 fontData->unref(); // SkRefPtr and OpenStream both took a ref.
439
440 int fontSize = fontData->getLength();
441
442#if defined (SK_SFNTLY_SUBSETTER)
443 // Generate glyph id array.
vandebo@chromium.org17e66e22011-07-27 20:59:55 +0000444 SkTDArray<uint32_t> glyphIDs;
vandebo@chromium.org1f165892011-07-26 02:11:41 +0000445 glyphIDs.push(0); // Always include glyph 0.
vandebo@chromium.org17e66e22011-07-27 20:59:55 +0000446 subset->exportTo(&glyphIDs);
vandebo@chromium.org1f165892011-07-26 02:11:41 +0000447
448 // Read font into buffer.
449 SkPDFStream* subsetFontStream = NULL;
450 SkTDArray<unsigned char> originalFont;
451 originalFont.setCount(fontSize);
452 if (fontData->read(originalFont.begin(), fontSize) == (size_t)fontSize) {
453 unsigned char* subsetFont = NULL;
vandebo@chromium.org17e66e22011-07-27 20:59:55 +0000454 // sfntly requires unsigned int* to be passed in, as far as we know,
455 // unsigned int is equivalent to uint32_t on all platforms.
456 SK_COMPILE_ASSERT(sizeof(unsigned int) == sizeof(uint32_t),
457 unsigned_int_not_32_bits);
vandebo@chromium.org1f165892011-07-26 02:11:41 +0000458 int subsetFontSize = SfntlyWrapper::SubsetFont(fontName,
459 originalFont.begin(),
460 fontSize,
461 glyphIDs.begin(),
462 glyphIDs.count(),
463 &subsetFont);
464 if (subsetFontSize > 0 && subsetFont != NULL) {
vandebo@chromium.org93225ff2011-07-27 18:38:11 +0000465 SkAutoDataUnref data(SkData::NewWithProc(subsetFont,
466 subsetFontSize,
467 sk_delete_array,
468 NULL));
469 subsetFontStream = new SkPDFStream(data.get());
vandebo@chromium.org1f165892011-07-26 02:11:41 +0000470 fontSize = subsetFontSize;
471 }
472 }
473 if (subsetFontStream) {
474 *fontStream = subsetFontStream;
475 return fontSize;
476 }
477#endif
478
479 // Fail over: just embed the whole font.
480 *fontStream = new SkPDFStream(fontData.get());
481 return fontSize;
482}
483
vandebo@chromium.org98594282011-07-25 22:34:12 +0000484///////////////////////////////////////////////////////////////////////////////
485// class SkPDFGlyphSet
486///////////////////////////////////////////////////////////////////////////////
487
488SkPDFGlyphSet::SkPDFGlyphSet() : fBitSet(SK_MaxU16 + 1) {
489}
490
491void SkPDFGlyphSet::set(const uint16_t* glyphIDs, int numGlyphs) {
492 for (int i = 0; i < numGlyphs; ++i) {
493 fBitSet.setBit(glyphIDs[i], true);
494 }
495}
496
497bool SkPDFGlyphSet::has(uint16_t glyphID) const {
498 return fBitSet.isBitSet(glyphID);
499}
500
501void SkPDFGlyphSet::merge(const SkPDFGlyphSet& usage) {
502 fBitSet.orBits(usage.fBitSet);
503}
504
vandebo@chromium.org17e66e22011-07-27 20:59:55 +0000505void SkPDFGlyphSet::exportTo(SkTDArray<unsigned int>* glyphIDs) const {
506 fBitSet.exportTo(glyphIDs);
507}
508
vandebo@chromium.org98594282011-07-25 22:34:12 +0000509///////////////////////////////////////////////////////////////////////////////
510// class SkPDFGlyphSetMap
511///////////////////////////////////////////////////////////////////////////////
512SkPDFGlyphSetMap::FontGlyphSetPair::FontGlyphSetPair(SkPDFFont* font,
513 SkPDFGlyphSet* glyphSet)
514 : fFont(font),
515 fGlyphSet(glyphSet) {
516}
517
518SkPDFGlyphSetMap::F2BIter::F2BIter(const SkPDFGlyphSetMap& map) {
519 reset(map);
520}
521
522SkPDFGlyphSetMap::FontGlyphSetPair* SkPDFGlyphSetMap::F2BIter::next() const {
523 if (fIndex >= fMap->count()) {
524 return NULL;
525 }
526 return &((*fMap)[fIndex++]);
527}
528
529void SkPDFGlyphSetMap::F2BIter::reset(const SkPDFGlyphSetMap& map) {
530 fMap = &(map.fMap);
531 fIndex = 0;
532}
533
534SkPDFGlyphSetMap::SkPDFGlyphSetMap() {
535}
536
537SkPDFGlyphSetMap::~SkPDFGlyphSetMap() {
538 reset();
539}
540
541void SkPDFGlyphSetMap::merge(const SkPDFGlyphSetMap& usage) {
542 for (int i = 0; i < usage.fMap.count(); ++i) {
543 SkPDFGlyphSet* myUsage = getGlyphSetForFont(usage.fMap[i].fFont);
544 myUsage->merge(*(usage.fMap[i].fGlyphSet));
545 }
546}
547
548void SkPDFGlyphSetMap::reset() {
549 for (int i = 0; i < fMap.count(); ++i) {
550 delete fMap[i].fGlyphSet; // Should not be NULL.
551 }
552 fMap.reset();
553}
554
555void SkPDFGlyphSetMap::noteGlyphUsage(SkPDFFont* font, const uint16_t* glyphIDs,
556 int numGlyphs) {
557 SkPDFGlyphSet* subset = getGlyphSetForFont(font);
558 if (subset) {
559 subset->set(glyphIDs, numGlyphs);
560 }
561}
562
563SkPDFGlyphSet* SkPDFGlyphSetMap::getGlyphSetForFont(SkPDFFont* font) {
564 int index = fMap.count();
565 for (int i = 0; i < index; ++i) {
566 if (fMap[i].fFont == font) {
567 return fMap[i].fGlyphSet;
568 }
569 }
570 fMap.append();
571 index = fMap.count() - 1;
572 fMap[index].fFont = font;
573 fMap[index].fGlyphSet = new SkPDFGlyphSet();
574 return fMap[index].fGlyphSet;
575}
576
577///////////////////////////////////////////////////////////////////////////////
578// class SkPDFFont
579///////////////////////////////////////////////////////////////////////////////
580
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000581/* Font subset design: It would be nice to be able to subset fonts
582 * (particularly type 3 fonts), but it's a lot of work and not a priority.
583 *
584 * Resources are canonicalized and uniqueified by pointer so there has to be
585 * some additional state indicating which subset of the font is used. It
586 * must be maintained at the page granularity and then combined at the document
587 * granularity. a) change SkPDFFont to fill in its state on demand, kind of
588 * like SkPDFGraphicState. b) maintain a per font glyph usage class in each
589 * page/pdf device. c) in the document, retrieve the per font glyph usage
590 * from each page and combine it and ask for a resource with that subset.
591 */
592
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000593SkPDFFont::~SkPDFFont() {
reed@google.comf6c3ebd2011-07-20 17:20:28 +0000594 SkAutoMutexAcquire lock(CanonicalFontsMutex());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000595 int index;
reed@google.comf6c3ebd2011-07-20 17:20:28 +0000596 if (Find(SkTypeface::UniqueID(fTypeface.get()), fFirstGlyphID, &index)) {
597 CanonicalFonts().removeShuffle(index);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000598 }
599 fResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000600}
601
602void SkPDFFont::getResources(SkTDArray<SkPDFObject*>* resourceList) {
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000603 GetResourcesHelper(&fResources, resourceList);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000604}
605
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000606SkTypeface* SkPDFFont::typeface() {
607 return fTypeface.get();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000608}
609
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +0000610SkAdvancedTypefaceMetrics::FontType SkPDFFont::getType() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000611 return fFontType;
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +0000612}
613
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000614bool SkPDFFont::hasGlyph(uint16_t id) {
615 return (id >= fFirstGlyphID && id <= fLastGlyphID) || id == 0;
616}
617
vandebo@chromium.org01294102011-02-28 19:52:18 +0000618size_t SkPDFFont::glyphsToPDFFontEncoding(uint16_t* glyphIDs,
619 size_t numGlyphs) {
620 // A font with multibyte glyphs will support all glyph IDs in a single font.
vandebo@chromium.org98594282011-07-25 22:34:12 +0000621 if (this->multiByteGlyphs()) {
vandebo@chromium.org01294102011-02-28 19:52:18 +0000622 return numGlyphs;
623 }
624
625 for (size_t i = 0; i < numGlyphs; i++) {
626 if (glyphIDs[i] == 0) {
627 continue;
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000628 }
vandebo@chromium.org01294102011-02-28 19:52:18 +0000629 if (glyphIDs[i] < fFirstGlyphID || glyphIDs[i] > fLastGlyphID) {
630 return i;
631 }
632 glyphIDs[i] -= (fFirstGlyphID - 1);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000633 }
634
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000635 return numGlyphs;
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000636}
637
638// static
reed@google.comf6c3ebd2011-07-20 17:20:28 +0000639SkPDFFont* SkPDFFont::GetFontResource(SkTypeface* typeface, uint16_t glyphID) {
640 SkAutoMutexAcquire lock(CanonicalFontsMutex());
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000641 const uint32_t fontID = SkTypeface::UniqueID(typeface);
vandebo@chromium.org98594282011-07-25 22:34:12 +0000642 int relatedFontIndex;
643 if (Find(fontID, glyphID, &relatedFontIndex)) {
644 CanonicalFonts()[relatedFontIndex].fFont->ref();
645 return CanonicalFonts()[relatedFontIndex].fFont;
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000646 }
647
vandebo@chromium.org98594282011-07-25 22:34:12 +0000648 SkRefPtr<SkAdvancedTypefaceMetrics> fontMetrics;
649 SkPDFDict* relatedFontDescriptor = NULL;
650 if (relatedFontIndex >= 0) {
651 SkPDFFont* relatedFont = CanonicalFonts()[relatedFontIndex].fFont;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000652 SkASSERT(relatedFont->fFontInfo.get());
vandebo@chromium.org98594282011-07-25 22:34:12 +0000653 fontMetrics = relatedFont->fontInfo();
654 relatedFontDescriptor = relatedFont->getFontDescriptor();
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000655 } else {
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000656 SkAdvancedTypefaceMetrics::PerGlyphInfo info;
657 info = SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo;
658 info = SkTBitOr<SkAdvancedTypefaceMetrics::PerGlyphInfo>(
659 info, SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo);
660 info = SkTBitOr<SkAdvancedTypefaceMetrics::PerGlyphInfo>(
661 info, SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo);
vandebo@chromium.org98594282011-07-25 22:34:12 +0000662 fontMetrics = SkFontHost::GetAdvancedTypefaceMetrics(fontID, info);
663 SkSafeUnref(fontMetrics.get()); // SkRefPtr and Get both took a ref.
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000664 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000665
vandebo@chromium.org98594282011-07-25 22:34:12 +0000666 SkPDFFont* font = Create(fontMetrics.get(), typeface, glyphID,
667 relatedFontDescriptor);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000668 FontRec newEntry(font, fontID, font->fFirstGlyphID);
reed@google.comf6c3ebd2011-07-20 17:20:28 +0000669 CanonicalFonts().push(newEntry);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000670 return font; // Return the reference new SkPDFFont() created.
671}
672
vandebo@chromium.org98594282011-07-25 22:34:12 +0000673SkPDFFont* SkPDFFont::getFontSubset(const SkPDFGlyphSet* usage) {
674 return NULL; // Default: no support.
675}
676
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000677// static
reed@google.comf6c3ebd2011-07-20 17:20:28 +0000678SkTDArray<SkPDFFont::FontRec>& SkPDFFont::CanonicalFonts() {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000679 // This initialization is only thread safe with gcc.
680 static SkTDArray<FontRec> gCanonicalFonts;
681 return gCanonicalFonts;
682}
683
684// static
reed@google.comf6c3ebd2011-07-20 17:20:28 +0000685SkMutex& SkPDFFont::CanonicalFontsMutex() {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000686 // This initialization is only thread safe with gcc.
687 static SkMutex gCanonicalFontsMutex;
688 return gCanonicalFontsMutex;
689}
690
691// static
reed@google.comf6c3ebd2011-07-20 17:20:28 +0000692bool SkPDFFont::Find(uint32_t fontID, uint16_t glyphID, int* index) {
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000693 // TODO(vandebo) optimize this, do only one search?
694 FontRec search(NULL, fontID, glyphID);
reed@google.comf6c3ebd2011-07-20 17:20:28 +0000695 *index = CanonicalFonts().find(search);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000696 if (*index >= 0)
697 return true;
698 search.fGlyphID = 0;
reed@google.comf6c3ebd2011-07-20 17:20:28 +0000699 *index = CanonicalFonts().find(search);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000700 return false;
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000701}
702
vandebo@chromium.org98594282011-07-25 22:34:12 +0000703SkPDFFont::SkPDFFont(SkAdvancedTypefaceMetrics* info, SkTypeface* typeface,
704 uint16_t glyphID, bool descendantFont)
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000705 : SkPDFDict("Font"),
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000706 fTypeface(typeface),
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000707 fFirstGlyphID(1),
vandebo@chromium.org98594282011-07-25 22:34:12 +0000708 fLastGlyphID(info ? info->fLastGlyphID : 0),
709 fFontInfo(info) {
710 if (info == NULL) {
711 fFontType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
712 } else if (info->fMultiMaster) {
713 fFontType = SkAdvancedTypefaceMetrics::kOther_Font;
714 } else {
715 fFontType = info->fType;
716 }
717}
718
719// static
720SkPDFFont* SkPDFFont::Create(SkAdvancedTypefaceMetrics* info,
721 SkTypeface* typeface, uint16_t glyphID,
722 SkPDFDict* relatedFontDescriptor) {
723 SkAdvancedTypefaceMetrics::FontType type =
724 info ? info->fType : SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
725
726 if (info && info->fMultiMaster) {
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +0000727 NOT_IMPLEMENTED(true, true);
vandebo@chromium.org98594282011-07-25 22:34:12 +0000728 return new SkPDFType3Font(info,
729 typeface,
730 glyphID,
731 relatedFontDescriptor);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000732 }
vandebo@chromium.org98594282011-07-25 22:34:12 +0000733 if (type == SkAdvancedTypefaceMetrics::kType1CID_Font ||
734 type == SkAdvancedTypefaceMetrics::kTrueType_Font) {
735 SkASSERT(relatedFontDescriptor == NULL);
736 return new SkPDFType0Font(info, typeface);
737 }
738 if (type == SkAdvancedTypefaceMetrics::kType1_Font) {
739 return new SkPDFType1Font(info,
740 typeface,
741 glyphID,
742 relatedFontDescriptor);
vandebo@chromium.org6504cfd2011-07-23 20:22:53 +0000743 }
vandebo@chromium.org31dcee72011-07-23 21:13:30 +0000744
vandebo@chromium.org98594282011-07-25 22:34:12 +0000745 SkASSERT(type == SkAdvancedTypefaceMetrics::kCFF_Font ||
746 type == SkAdvancedTypefaceMetrics::kOther_Font ||
747 type == SkAdvancedTypefaceMetrics::kNotEmbeddable_Font);
vandebo@chromium.org31dcee72011-07-23 21:13:30 +0000748
vandebo@chromium.org98594282011-07-25 22:34:12 +0000749 return new SkPDFType3Font(info, typeface, glyphID, relatedFontDescriptor);
vandebo@chromium.org31dcee72011-07-23 21:13:30 +0000750}
751
vandebo@chromium.org98594282011-07-25 22:34:12 +0000752SkAdvancedTypefaceMetrics* SkPDFFont::fontInfo() {
753 return fFontInfo.get();
vandebo@chromium.org31dcee72011-07-23 21:13:30 +0000754}
755
vandebo@chromium.org98594282011-07-25 22:34:12 +0000756uint16_t SkPDFFont::firstGlyphID() const {
757 return fFirstGlyphID;
758}
759
760uint16_t SkPDFFont::lastGlyphID() const {
761 return fLastGlyphID;
762}
763
764void SkPDFFont::setLastGlyphID(uint16_t glyphID) {
765 fLastGlyphID = glyphID;
766}
767
768void SkPDFFont::addResource(SkPDFObject* object) {
769 SkASSERT(object != NULL);
770 fResources.push(object);
771}
772
773SkPDFDict* SkPDFFont::getFontDescriptor() {
774 return fDescriptor.get();
775}
776
777void SkPDFFont::setFontDescriptor(SkPDFDict* descriptor) {
778 fDescriptor = descriptor;
779}
780
781bool SkPDFFont::addCommonFontDescriptorEntries(int16_t defaultWidth) {
782 if (fDescriptor.get() == NULL) {
783 return false;
vandebo@chromium.org31dcee72011-07-23 21:13:30 +0000784 }
785
vandebo@chromium.org98594282011-07-25 22:34:12 +0000786 const uint16_t emSize = fFontInfo->fEmSize;
787
788 fDescriptor->insertName("FontName", fFontInfo->fFontName);
789 fDescriptor->insertInt("Flags", fFontInfo->fStyle);
790 fDescriptor->insertScalar("Ascent",
791 scaleFromFontUnits(fFontInfo->fAscent, emSize));
792 fDescriptor->insertScalar("Descent",
793 scaleFromFontUnits(fFontInfo->fDescent, emSize));
794 fDescriptor->insertScalar("StemV",
795 scaleFromFontUnits(fFontInfo->fStemV, emSize));
796 fDescriptor->insertScalar("CapHeight",
797 scaleFromFontUnits(fFontInfo->fCapHeight, emSize));
798 fDescriptor->insertInt("ItalicAngle", fFontInfo->fItalicAngle);
799 fDescriptor->insert("FontBBox", makeFontBBox(fFontInfo->fBBox,
800 fFontInfo->fEmSize))->unref();
801
802 if (defaultWidth > 0) {
803 fDescriptor->insertScalar("MissingWidth",
804 scaleFromFontUnits(defaultWidth, emSize));
805 }
806 return true;
807}
808
809void SkPDFFont::adjustGlyphRangeForSingleByteEncoding(int16_t glyphID) {
810 // Single byte glyph encoding supports a max of 255 glyphs.
811 fFirstGlyphID = glyphID - (glyphID - 1) % 255;
812 if (fLastGlyphID > fFirstGlyphID + 255 - 1) {
813 fLastGlyphID = fFirstGlyphID + 255 - 1;
814 }
815}
816
817bool SkPDFFont::FontRec::operator==(const SkPDFFont::FontRec& b) const {
818 if (fFontID != b.fFontID)
819 return false;
820 if (fFont != NULL && b.fFont != NULL) {
821 return fFont->fFirstGlyphID == b.fFont->fFirstGlyphID &&
822 fFont->fLastGlyphID == b.fFont->fLastGlyphID;
823 }
824 if (fGlyphID == 0 || b.fGlyphID == 0)
825 return true;
826
827 if (fFont != NULL) {
828 return fFont->fFirstGlyphID <= b.fGlyphID &&
829 b.fGlyphID <= fFont->fLastGlyphID;
830 } else if (b.fFont != NULL) {
831 return b.fFont->fFirstGlyphID <= fGlyphID &&
832 fGlyphID <= b.fFont->fLastGlyphID;
833 }
834 return fGlyphID == b.fGlyphID;
835}
836
837SkPDFFont::FontRec::FontRec(SkPDFFont* font, uint32_t fontID, uint16_t glyphID)
838 : fFont(font),
839 fFontID(fontID),
840 fGlyphID(glyphID) {
841}
842
843void SkPDFFont::populateToUnicodeTable(const SkPDFGlyphSet* subset) {
844 if (fFontInfo == NULL || fFontInfo->fGlyphToUnicode.begin() == NULL) {
845 return;
846 }
847 SkRefPtr<SkPDFStream> pdfCmap =
848 generate_tounicode_cmap(fFontInfo->fGlyphToUnicode, subset);
849 addResource(pdfCmap.get()); // Pass reference from new.
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000850 insert("ToUnicode", new SkPDFObjRef(pdfCmap.get()))->unref();
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000851}
852
vandebo@chromium.org98594282011-07-25 22:34:12 +0000853///////////////////////////////////////////////////////////////////////////////
854// class SkPDFType0Font
855///////////////////////////////////////////////////////////////////////////////
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +0000856
vandebo@chromium.org98594282011-07-25 22:34:12 +0000857SkPDFType0Font::SkPDFType0Font(SkAdvancedTypefaceMetrics* info,
858 SkTypeface* typeface)
859 : SkPDFFont(info, typeface, 0, false) {
860 SkDEBUGCODE(fPopulated = false);
861}
862
863SkPDFType0Font::~SkPDFType0Font() {}
864
865SkPDFFont* SkPDFType0Font::getFontSubset(const SkPDFGlyphSet* subset) {
866 SkPDFType0Font* newSubset = new SkPDFType0Font(fontInfo(), typeface());
867 newSubset->populate(subset);
868 return newSubset;
869}
870
871#ifdef SK_DEBUG
872void SkPDFType0Font::emitObject(SkWStream* stream, SkPDFCatalog* catalog,
873 bool indirect) {
874 SkASSERT(fPopulated);
875 return INHERITED::emitObject(stream, catalog, indirect);
876}
877#endif
878
879bool SkPDFType0Font::populate(const SkPDFGlyphSet* subset) {
880 insertName("Subtype", "Type0");
881 insertName("BaseFont", fontInfo()->fFontName);
882 insertName("Encoding", "Identity-H");
883
884 // Pass ref new created to fResources.
885 SkPDFCIDFont* newCIDFont =
886 new SkPDFCIDFont(fontInfo(), typeface(), subset);
887 addResource(newCIDFont);
888 SkRefPtr<SkPDFArray> descendantFonts = new SkPDFArray();
889 descendantFonts->unref(); // SkRefPtr and new took a reference.
890 descendantFonts->append(new SkPDFObjRef(newCIDFont))->unref();
891 insert("DescendantFonts", descendantFonts.get());
892
893 populateToUnicodeTable(subset);
894
895 SkDEBUGCODE(fPopulated = true);
896 return true;
897}
898
899///////////////////////////////////////////////////////////////////////////////
900// class SkPDFCIDFont
901///////////////////////////////////////////////////////////////////////////////
902
903SkPDFCIDFont::SkPDFCIDFont(SkAdvancedTypefaceMetrics* info,
904 SkTypeface* typeface, const SkPDFGlyphSet* subset)
905 : SkPDFFont(info, typeface, 0, true) {
906 populate(subset);
907}
908
909SkPDFCIDFont::~SkPDFCIDFont() {}
910
911bool SkPDFCIDFont::addFontDescriptor(int16_t defaultWidth,
912 const SkPDFGlyphSet* subset) {
913 SkRefPtr<SkPDFDict> descriptor = new SkPDFDict("FontDescriptor");
914 descriptor->unref(); // SkRefPtr and new both took a ref.
915 setFontDescriptor(descriptor.get());
916
917 switch (getType()) {
918 case SkAdvancedTypefaceMetrics::kTrueType_Font: {
vandebo@chromium.org1f165892011-07-26 02:11:41 +0000919 // Font subsetting
920 SkPDFStream* rawStream = NULL;
921 int fontSize = get_subset_font_stream(fontInfo()->fFontName.c_str(),
922 typeface(),
923 subset,
924 &rawStream);
925 SkASSERT(fontSize);
926 SkASSERT(rawStream);
927 SkRefPtr<SkPDFStream> fontStream = rawStream;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000928 // SkRefPtr and new both ref()'d fontStream, pass one.
929 addResource(fontStream.get());
930
vandebo@chromium.org1f165892011-07-26 02:11:41 +0000931 fontStream->insertInt("Length1", fontSize);
vandebo@chromium.org98594282011-07-25 22:34:12 +0000932 descriptor->insert("FontFile2",
933 new SkPDFObjRef(fontStream.get()))->unref();
934 break;
935 }
936 case SkAdvancedTypefaceMetrics::kCFF_Font:
937 case SkAdvancedTypefaceMetrics::kType1CID_Font: {
938 SkRefPtr<SkStream> fontData =
939 SkFontHost::OpenStream(SkTypeface::UniqueID(typeface()));
940 fontData->unref(); // SkRefPtr and OpenStream both took a ref.
941 SkRefPtr<SkPDFStream> fontStream = new SkPDFStream(fontData.get());
942 // SkRefPtr and new both ref()'d fontStream, pass one.
943 addResource(fontStream.get());
944
945 if (getType() == SkAdvancedTypefaceMetrics::kCFF_Font) {
946 fontStream->insertName("Subtype", "Type1C");
947 } else {
948 fontStream->insertName("Subtype", "CIDFontType0c");
949 }
950 descriptor->insert("FontFile3",
951 new SkPDFObjRef(fontStream.get()))->unref();
952 break;
953 }
954 default:
955 SkASSERT(false);
956 }
957
958 addResource(descriptor.get());
959 descriptor->ref();
960
961 insert("FontDescriptor", new SkPDFObjRef(descriptor.get()))->unref();
962 return addCommonFontDescriptorEntries(defaultWidth);
963}
964
965bool SkPDFCIDFont::populate(const SkPDFGlyphSet* subset) {
966 insertName("BaseFont", fontInfo()->fFontName);
967
968 if (getType() == SkAdvancedTypefaceMetrics::kType1CID_Font) {
reed@google.comc789cf12011-07-20 12:14:33 +0000969 insertName("Subtype", "CIDFontType0");
vandebo@chromium.org98594282011-07-25 22:34:12 +0000970 } else if (getType() == SkAdvancedTypefaceMetrics::kTrueType_Font) {
reed@google.comc789cf12011-07-20 12:14:33 +0000971 insertName("Subtype", "CIDFontType2");
972 insertName("CIDToGIDMap", "Identity");
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000973 } else {
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000974 SkASSERT(false);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000975 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000976
977 SkRefPtr<SkPDFDict> sysInfo = new SkPDFDict;
978 sysInfo->unref(); // SkRefPtr and new both took a reference.
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +0000979 sysInfo->insert("Registry", new SkPDFString("Adobe"))->unref();
980 sysInfo->insert("Ordering", new SkPDFString("Identity"))->unref();
reed@google.comc789cf12011-07-20 12:14:33 +0000981 sysInfo->insertInt("Supplement", 0);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000982 insert("CIDSystemInfo", sysInfo.get());
983
vandebo@chromium.org98594282011-07-25 22:34:12 +0000984 addFontDescriptor(0, subset);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000985
vandebo@chromium.org98594282011-07-25 22:34:12 +0000986 if (fontInfo()->fGlyphWidths.get()) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000987 int16_t defaultWidth = 0;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000988 SkRefPtr<SkPDFArray> widths =
vandebo@chromium.org98594282011-07-25 22:34:12 +0000989 composeAdvanceData(fontInfo()->fGlyphWidths.get(),
990 fontInfo()->fEmSize, &appendWidth,
991 &defaultWidth);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000992 widths->unref(); // SkRefPtr and compose both took a reference.
993 if (widths->size())
994 insert("W", widths.get());
995 if (defaultWidth != 0) {
reed@google.comc789cf12011-07-20 12:14:33 +0000996 insertScalar("DW", scaleFromFontUnits(defaultWidth,
vandebo@chromium.org98594282011-07-25 22:34:12 +0000997 fontInfo()->fEmSize));
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000998 }
999 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001000 if (fontInfo()->fVerticalMetrics.get()) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +00001001 struct SkAdvancedTypefaceMetrics::VerticalMetric defaultAdvance;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001002 defaultAdvance.fVerticalAdvance = 0;
1003 defaultAdvance.fOriginXDisp = 0;
1004 defaultAdvance.fOriginYDisp = 0;
1005 SkRefPtr<SkPDFArray> advances =
vandebo@chromium.org98594282011-07-25 22:34:12 +00001006 composeAdvanceData(fontInfo()->fVerticalMetrics.get(),
1007 fontInfo()->fEmSize, &appendVerticalAdvance,
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001008 &defaultAdvance);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001009 advances->unref(); // SkRefPtr and compose both took a ref.
1010 if (advances->size())
1011 insert("W2", advances.get());
1012 if (defaultAdvance.fVerticalAdvance ||
1013 defaultAdvance.fOriginXDisp ||
1014 defaultAdvance.fOriginYDisp) {
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001015 insert("DW2", appendVerticalAdvance(defaultAdvance,
vandebo@chromium.org98594282011-07-25 22:34:12 +00001016 fontInfo()->fEmSize,
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001017 new SkPDFArray))->unref();
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001018 }
1019 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001020
1021 return true;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001022}
1023
vandebo@chromium.org98594282011-07-25 22:34:12 +00001024///////////////////////////////////////////////////////////////////////////////
1025// class SkPDFType1Font
1026///////////////////////////////////////////////////////////////////////////////
1027
1028SkPDFType1Font::SkPDFType1Font(SkAdvancedTypefaceMetrics* info,
1029 SkTypeface* typeface,
1030 uint16_t glyphID,
1031 SkPDFDict* relatedFontDescriptor)
1032 : SkPDFFont(info, typeface, glyphID, false) {
1033 populate(glyphID);
1034}
1035
1036SkPDFType1Font::~SkPDFType1Font() {}
1037
1038bool SkPDFType1Font::addFontDescriptor(int16_t defaultWidth) {
1039 SkRefPtr<SkPDFDict> descriptor = getFontDescriptor();
1040 if (descriptor.get() != NULL) {
1041 addResource(descriptor.get());
1042 descriptor->ref();
1043 insert("FontDescriptor", new SkPDFObjRef(descriptor.get()))->unref();
1044 return true;
1045 }
1046
1047 descriptor = new SkPDFDict("FontDescriptor");
1048 descriptor->unref(); // SkRefPtr and new both took a ref.
1049 setFontDescriptor(descriptor.get());
1050
1051 size_t header SK_INIT_TO_AVOID_WARNING;
1052 size_t data SK_INIT_TO_AVOID_WARNING;
1053 size_t trailer SK_INIT_TO_AVOID_WARNING;
1054 SkRefPtr<SkStream> rawFontData =
1055 SkFontHost::OpenStream(SkTypeface::UniqueID(typeface()));
1056 rawFontData->unref(); // SkRefPtr and OpenStream both took a ref.
1057 SkStream* fontData = handleType1Stream(rawFontData.get(), &header, &data,
1058 &trailer);
1059 if (fontData == NULL) {
1060 return false;
1061 }
1062 SkRefPtr<SkPDFStream> fontStream = new SkPDFStream(fontData);
1063 // SkRefPtr and new both ref()'d fontStream, pass one.
1064 addResource(fontStream.get());
1065 fontStream->insertInt("Length1", header);
1066 fontStream->insertInt("Length2", data);
1067 fontStream->insertInt("Length3", trailer);
1068 descriptor->insert("FontFile", new SkPDFObjRef(fontStream.get()))->unref();
1069
1070 addResource(descriptor.get());
1071 descriptor->ref();
1072 insert("FontDescriptor", new SkPDFObjRef(descriptor.get()))->unref();
1073
1074 return addCommonFontDescriptorEntries(defaultWidth);
1075}
1076
1077bool SkPDFType1Font::populate(int16_t glyphID) {
1078 SkASSERT(!fontInfo()->fVerticalMetrics.get());
1079 SkASSERT(fontInfo()->fGlyphWidths.get());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001080
vandebo@chromium.orgf77e27d2011-03-10 22:50:28 +00001081 adjustGlyphRangeForSingleByteEncoding(glyphID);
1082
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +00001083 int16_t defaultWidth = 0;
1084 const SkAdvancedTypefaceMetrics::WidthRange* widthRangeEntry = NULL;
1085 const SkAdvancedTypefaceMetrics::WidthRange* widthEntry;
vandebo@chromium.org98594282011-07-25 22:34:12 +00001086 for (widthEntry = fontInfo()->fGlyphWidths.get();
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001087 widthEntry != NULL;
1088 widthEntry = widthEntry->fNext.get()) {
1089 switch (widthEntry->fType) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +00001090 case SkAdvancedTypefaceMetrics::WidthRange::kDefault:
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001091 defaultWidth = widthEntry->fAdvance[0];
1092 break;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +00001093 case SkAdvancedTypefaceMetrics::WidthRange::kRun:
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001094 SkASSERT(false);
1095 break;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +00001096 case SkAdvancedTypefaceMetrics::WidthRange::kRange:
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001097 SkASSERT(widthRangeEntry == NULL);
1098 widthRangeEntry = widthEntry;
1099 break;
1100 }
1101 }
1102
1103 if (!addFontDescriptor(defaultWidth))
1104 return false;
1105
reed@google.comc789cf12011-07-20 12:14:33 +00001106 insertName("Subtype", "Type1");
vandebo@chromium.org98594282011-07-25 22:34:12 +00001107 insertName("BaseFont", fontInfo()->fFontName);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001108
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001109 addWidthInfoFromRange(defaultWidth, widthRangeEntry);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001110
1111 SkRefPtr<SkPDFDict> encoding = new SkPDFDict("Encoding");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001112 encoding->unref(); // SkRefPtr and new both took a reference.
1113 insert("Encoding", encoding.get());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001114
1115 SkRefPtr<SkPDFArray> encDiffs = new SkPDFArray;
1116 encDiffs->unref(); // SkRefPtr and new both took a reference.
1117 encoding->insert("Differences", encDiffs.get());
1118
vandebo@chromium.org98594282011-07-25 22:34:12 +00001119 encDiffs->reserve(lastGlyphID() - firstGlyphID() + 2);
reed@google.comc789cf12011-07-20 12:14:33 +00001120 encDiffs->appendInt(1);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001121 for (int gID = firstGlyphID(); gID <= lastGlyphID(); gID++) {
1122 encDiffs->appendName(fontInfo()->fGlyphNames->get()[gID].c_str());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001123 }
1124
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001125 return true;
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001126}
1127
vandebo@chromium.org98594282011-07-25 22:34:12 +00001128void SkPDFType1Font::addWidthInfoFromRange(
1129 int16_t defaultWidth,
1130 const SkAdvancedTypefaceMetrics::WidthRange* widthRangeEntry) {
1131 SkRefPtr<SkPDFArray> widthArray = new SkPDFArray();
1132 widthArray->unref(); // SkRefPtr and new both took a ref.
1133 int firstChar = 0;
1134 if (widthRangeEntry) {
1135 const uint16_t emSize = fontInfo()->fEmSize;
1136 int startIndex = firstGlyphID() - widthRangeEntry->fStartId;
1137 int endIndex = startIndex + lastGlyphID() - firstGlyphID() + 1;
1138 if (startIndex < 0)
1139 startIndex = 0;
1140 if (endIndex > widthRangeEntry->fAdvance.count())
1141 endIndex = widthRangeEntry->fAdvance.count();
1142 if (widthRangeEntry->fStartId == 0) {
1143 appendWidth(widthRangeEntry->fAdvance[0], emSize, widthArray.get());
1144 } else {
1145 firstChar = startIndex + widthRangeEntry->fStartId;
1146 }
1147 for (int i = startIndex; i < endIndex; i++)
1148 appendWidth(widthRangeEntry->fAdvance[i], emSize, widthArray.get());
1149 } else {
1150 appendWidth(defaultWidth, 1000, widthArray.get());
1151 }
1152 insertInt("FirstChar", firstChar);
1153 insertInt("LastChar", firstChar + widthArray->size() - 1);
1154 insert("Widths", widthArray.get());
1155}
1156
1157///////////////////////////////////////////////////////////////////////////////
1158// class SkPDFType3Font
1159///////////////////////////////////////////////////////////////////////////////
1160
1161SkPDFType3Font::SkPDFType3Font(SkAdvancedTypefaceMetrics* info,
1162 SkTypeface* typeface,
1163 uint16_t glyphID,
1164 SkPDFDict* relatedFontDescriptor)
1165 : SkPDFFont(info, typeface, glyphID, false) {
1166 populate(glyphID);
1167}
1168
1169SkPDFType3Font::~SkPDFType3Font() {}
1170
1171bool SkPDFType3Font::populate(int16_t glyphID) {
vandebo@chromium.orgf77e27d2011-03-10 22:50:28 +00001172 SkPaint paint;
vandebo@chromium.org98594282011-07-25 22:34:12 +00001173 paint.setTypeface(typeface());
vandebo@chromium.orgf77e27d2011-03-10 22:50:28 +00001174 paint.setTextSize(1000);
1175 SkAutoGlyphCache autoCache(paint, NULL);
1176 SkGlyphCache* cache = autoCache.getCache();
1177 // If fLastGlyphID isn't set (because there is not fFontInfo), look it up.
vandebo@chromium.org98594282011-07-25 22:34:12 +00001178 if (lastGlyphID() == 0) {
1179 setLastGlyphID(cache->getGlyphCount() - 1);
vandebo@chromium.orgf77e27d2011-03-10 22:50:28 +00001180 }
1181
1182 adjustGlyphRangeForSingleByteEncoding(glyphID);
1183
reed@google.comc789cf12011-07-20 12:14:33 +00001184 insertName("Subtype", "Type3");
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001185 // Flip about the x-axis and scale by 1/1000.
1186 SkMatrix fontMatrix;
1187 fontMatrix.setScale(SkScalarInvert(1000), -SkScalarInvert(1000));
1188 insert("FontMatrix", SkPDFUtils::MatrixToArray(fontMatrix))->unref();
1189
1190 SkRefPtr<SkPDFDict> charProcs = new SkPDFDict;
1191 charProcs->unref(); // SkRefPtr and new both took a reference.
1192 insert("CharProcs", charProcs.get());
1193
1194 SkRefPtr<SkPDFDict> encoding = new SkPDFDict("Encoding");
1195 encoding->unref(); // SkRefPtr and new both took a reference.
1196 insert("Encoding", encoding.get());
1197
1198 SkRefPtr<SkPDFArray> encDiffs = new SkPDFArray;
1199 encDiffs->unref(); // SkRefPtr and new both took a reference.
1200 encoding->insert("Differences", encDiffs.get());
vandebo@chromium.org98594282011-07-25 22:34:12 +00001201 encDiffs->reserve(lastGlyphID() - firstGlyphID() + 2);
reed@google.comc789cf12011-07-20 12:14:33 +00001202 encDiffs->appendInt(1);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001203
1204 SkRefPtr<SkPDFArray> widthArray = new SkPDFArray();
1205 widthArray->unref(); // SkRefPtr and new both took a ref.
1206
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001207 SkIRect bbox = SkIRect::MakeEmpty();
vandebo@chromium.org98594282011-07-25 22:34:12 +00001208 for (int gID = firstGlyphID(); gID <= lastGlyphID(); gID++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001209 SkString characterName;
1210 characterName.printf("gid%d", gID);
reed@google.comc789cf12011-07-20 12:14:33 +00001211 encDiffs->appendName(characterName.c_str());
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001212
reed@google.comce11b262011-03-21 21:25:35 +00001213 const SkGlyph& glyph = cache->getGlyphIDMetrics(gID);
reed@google.comc789cf12011-07-20 12:14:33 +00001214 widthArray->appendScalar(SkFixedToScalar(glyph.fAdvanceX));
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001215 SkIRect glyphBBox = SkIRect::MakeXYWH(glyph.fLeft, glyph.fTop,
1216 glyph.fWidth, glyph.fHeight);
1217 bbox.join(glyphBBox);
1218
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001219 SkDynamicMemoryWStream content;
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001220 setGlyphWidthAndBoundingBox(SkFixedToScalar(glyph.fAdvanceX), glyphBBox,
1221 &content);
1222 const SkPath* path = cache->findPath(glyph);
1223 if (path) {
1224 SkPDFUtils::EmitPath(*path, &content);
1225 SkPDFUtils::PaintPath(paint.getStyle(), path->getFillType(),
1226 &content);
1227 }
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001228 SkRefPtr<SkMemoryStream> glyphStream = new SkMemoryStream();
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001229 glyphStream->unref(); // SkRefPtr and new both took a ref.
reed@google.com8a85d0c2011-06-24 19:12:12 +00001230 glyphStream->setData(content.copyToData())->unref();
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001231
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001232 SkRefPtr<SkPDFStream> glyphDescription =
1233 new SkPDFStream(glyphStream.get());
1234 // SkRefPtr and new both ref()'d charProcs, pass one.
vandebo@chromium.org98594282011-07-25 22:34:12 +00001235 addResource(glyphDescription.get());
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001236 charProcs->insert(characterName.c_str(),
1237 new SkPDFObjRef(glyphDescription.get()))->unref();
1238 }
1239
1240 insert("FontBBox", makeFontBBox(bbox, 1000))->unref();
vandebo@chromium.org98594282011-07-25 22:34:12 +00001241 insertInt("FirstChar", firstGlyphID());
1242 insertInt("LastChar", lastGlyphID());
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001243 insert("Widths", widthArray.get());
reed@google.comc789cf12011-07-20 12:14:33 +00001244 insertName("CIDToGIDMap", "Identity");
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001245
vandebo@chromium.org98594282011-07-25 22:34:12 +00001246 populateToUnicodeTable(NULL);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001247 return true;
1248}