blob: dd8ec442b5daaba9d8d5863007e82a88143845d2 [file] [log] [blame]
edisonn@google.com3aac1f92013-07-02 22:42:53 +00001#include "SkNativeParsedPDF.h"
edisonn@google.com571c70b2013-07-10 17:09:50 +00002#include "SkPdfNativeTokenizer.h"
3#include "SkPdfBasics.h"
edisonn@google.com571c70b2013-07-10 17:09:50 +00004#include "SkPdfObject.h"
edisonn@google.com3aac1f92013-07-02 22:42:53 +00005
edisonn@google.com571c70b2013-07-10 17:09:50 +00006#include <stdio.h>
7#include <string.h>
8#include <sys/types.h>
9#include <sys/stat.h>
edisonn@google.com3aac1f92013-07-02 22:42:53 +000010
edisonn@google.com571c70b2013-07-10 17:09:50 +000011#include "SkPdfFileTrailerDictionary_autogen.h"
12#include "SkPdfCatalogDictionary_autogen.h"
13#include "SkPdfPageObjectDictionary_autogen.h"
14#include "SkPdfPageTreeNodeDictionary_autogen.h"
15#include "SkPdfMapper_autogen.h"
16
17
18
edisonn@google.coma3356fc2013-07-10 18:20:06 +000019static long getFileSize(const char* filename)
edisonn@google.com571c70b2013-07-10 17:09:50 +000020{
21 struct stat stat_buf;
22 int rc = stat(filename, &stat_buf);
edisonn@google.coma3356fc2013-07-10 18:20:06 +000023 return rc == 0 ? (long)stat_buf.st_size : -1;
edisonn@google.com3aac1f92013-07-02 22:42:53 +000024}
25
edisonn@google.coma3356fc2013-07-10 18:20:06 +000026static unsigned char* lineHome(unsigned char* start, unsigned char* current) {
edisonn@google.com571c70b2013-07-10 17:09:50 +000027 while (current > start && !isPdfEOL(*(current - 1))) {
28 current--;
29 }
30 return current;
31}
32
edisonn@google.coma3356fc2013-07-10 18:20:06 +000033static unsigned char* previousLineHome(unsigned char* start, unsigned char* current) {
edisonn@google.com571c70b2013-07-10 17:09:50 +000034 if (current > start && isPdfEOL(*(current - 1))) {
35 current--;
36 }
37
38 // allows CR+LF, LF+CR but not two CR+CR or LF+LF
39 if (current > start && isPdfEOL(*(current - 1)) && *current != *(current - 1)) {
40 current--;
41 }
42
43 while (current > start && !isPdfEOL(*(current - 1))) {
44 current--;
45 }
46
47 return current;
48}
49
edisonn@google.coma3356fc2013-07-10 18:20:06 +000050static unsigned char* ignoreLine(unsigned char* current, unsigned char* end) {
edisonn@google.com571c70b2013-07-10 17:09:50 +000051 while (current < end && !isPdfEOL(*current)) {
52 current++;
53 }
54 current++;
55 if (current < end && isPdfEOL(*current) && *current != *(current - 1)) {
56 current++;
57 }
58 return current;
59}
60
edisonn@google.com222382b2013-07-10 22:33:10 +000061SkNativeParsedPDF* gDoc = NULL;
edisonn@google.com571c70b2013-07-10 17:09:50 +000062
63// TODO(edisonn): NYI
64// TODO(edisonn): 3 constructuctors from URL, from stream, from file ...
65// TODO(edisonn): write one that accepts errors in the file and ignores/fixis them
66// TODO(edisonn): testing:
67// 1) run on a lot of file
68// 2) recoverable corupt file: remove endobj, endsteam, remove other keywords, use other white spaces, insert comments randomly, ...
69// 3) irrecoverable corrupt file
edisonn@google.com432640a2013-07-10 22:53:40 +000070SkNativeParsedPDF::SkNativeParsedPDF(const char* path)
71 : fAllocator(new SkPdfAllocator())
72 , fRootCatalogRef(NULL)
73 , fRootCatalog(NULL) {
edisonn@google.com222382b2013-07-10 22:33:10 +000074 gDoc = this;
edisonn@google.com571c70b2013-07-10 17:09:50 +000075 FILE* file = fopen(path, "r");
76 fContentLength = getFileSize(path);
edisonn@google.com222382b2013-07-10 22:33:10 +000077 fFileContent = new unsigned char[fContentLength + 1];
edisonn@google.com571c70b2013-07-10 17:09:50 +000078 fread(fFileContent, fContentLength, 1, file);
edisonn@google.com222382b2013-07-10 22:33:10 +000079 fFileContent[fContentLength] = '\0';
edisonn@google.com571c70b2013-07-10 17:09:50 +000080 fclose(file);
81 file = NULL;
82
83 unsigned char* eofLine = lineHome(fFileContent, fFileContent + fContentLength - 1);
84 unsigned char* xrefByteOffsetLine = previousLineHome(fFileContent, eofLine);
85 unsigned char* xrefstartKeywordLine = previousLineHome(fFileContent, xrefByteOffsetLine);
86
87 if (strcmp((char*)xrefstartKeywordLine, "startxref") != 0) {
88 // TODO(edisonn): report/issue
89 }
90
91 long xrefByteOffset = atol((const char*)xrefByteOffsetLine);
92
93 bool storeCatalog = true;
94 while (xrefByteOffset >= 0) {
95 unsigned char* trailerStart = readCrossReferenceSection(fFileContent + xrefByteOffset, xrefstartKeywordLine);
96 xrefByteOffset = readTrailer(trailerStart, xrefstartKeywordLine, storeCatalog);
97 storeCatalog = false;
98 }
99
100 // TODO(edisonn): warn/error expect fObjects[fRefCatalogId].fGeneration == fRefCatalogGeneration
101 // TODO(edisonn): security, verify that SkPdfCatalogDictionary is indeed using mapper
102 // load catalog
edisonn@google.com571c70b2013-07-10 17:09:50 +0000103
edisonn@google.com432640a2013-07-10 22:53:40 +0000104 if (fRootCatalogRef) {
105 fRootCatalog = (SkPdfCatalogDictionary*)resolveReference(fRootCatalogRef);
edisonn@google.com8bad7372013-07-10 23:36:56 +0000106 if (fRootCatalog->isDictionary() && fRootCatalog->valid()) {
107 SkPdfPageTreeNodeDictionary* tree = fRootCatalog->Pages(this);
108 if (tree && tree->isDictionary() && tree->valid()) {
109 fillPages(tree);
110 }
111 }
edisonn@google.com432640a2013-07-10 22:53:40 +0000112 }
edisonn@google.com571c70b2013-07-10 17:09:50 +0000113
edisonn@google.com8bad7372013-07-10 23:36:56 +0000114 // TODO(edisonn): corrupted pdf, read it from beginning and rebuild (xref, trailer, or just reall all objects)
115 // 0 pages
116
edisonn@google.com571c70b2013-07-10 17:09:50 +0000117 // now actually read all objects if we want, or do it lazyly
118 // and resolve references?... or not ...
119}
120
121// TODO(edisonn): NYI
edisonn@google.com3aac1f92013-07-02 22:42:53 +0000122SkNativeParsedPDF::~SkNativeParsedPDF() {
edisonn@google.com571c70b2013-07-10 17:09:50 +0000123 delete[] fFileContent;
124 delete fAllocator;
125}
126
127unsigned char* SkNativeParsedPDF::readCrossReferenceSection(unsigned char* xrefStart, unsigned char* trailerEnd) {
128 unsigned char* current = ignoreLine(xrefStart, trailerEnd); // TODO(edisonn): verify next keyord is "xref", use nextObject here
129
130 SkPdfObject token;
131 while (current < trailerEnd) {
132 token.reset();
133 unsigned char* previous = current;
edisonn@google.com951d6532013-07-10 23:17:31 +0000134 current = nextObject(current, trailerEnd, &token, NULL, NULL);
edisonn@google.com571c70b2013-07-10 17:09:50 +0000135 if (!token.isInteger()) {
136 return previous;
137 }
138
edisonn@google.coma3356fc2013-07-10 18:20:06 +0000139 int startId = (int)token.intValue();
edisonn@google.com571c70b2013-07-10 17:09:50 +0000140 token.reset();
edisonn@google.com951d6532013-07-10 23:17:31 +0000141 current = nextObject(current, trailerEnd, &token, NULL, NULL);
edisonn@google.com571c70b2013-07-10 17:09:50 +0000142
143 if (!token.isInteger()) {
144 // TODO(edisonn): report/warning
145 return current;
146 }
147
edisonn@google.coma3356fc2013-07-10 18:20:06 +0000148 int entries = (int)token.intValue();
edisonn@google.com571c70b2013-07-10 17:09:50 +0000149
150 for (int i = 0; i < entries; i++) {
151 token.reset();
edisonn@google.com951d6532013-07-10 23:17:31 +0000152 current = nextObject(current, trailerEnd, &token, NULL, NULL);
edisonn@google.com571c70b2013-07-10 17:09:50 +0000153 if (!token.isInteger()) {
154 // TODO(edisonn): report/warning
155 return current;
156 }
edisonn@google.coma3356fc2013-07-10 18:20:06 +0000157 int offset = (int)token.intValue();
edisonn@google.com571c70b2013-07-10 17:09:50 +0000158
159 token.reset();
edisonn@google.com951d6532013-07-10 23:17:31 +0000160 current = nextObject(current, trailerEnd, &token, NULL, NULL);
edisonn@google.com571c70b2013-07-10 17:09:50 +0000161 if (!token.isInteger()) {
162 // TODO(edisonn): report/warning
163 return current;
164 }
edisonn@google.coma3356fc2013-07-10 18:20:06 +0000165 int generation = (int)token.intValue();
edisonn@google.com571c70b2013-07-10 17:09:50 +0000166
167 token.reset();
edisonn@google.com951d6532013-07-10 23:17:31 +0000168 current = nextObject(current, trailerEnd, &token, NULL, NULL);
edisonn@google.com571c70b2013-07-10 17:09:50 +0000169 if (!token.isKeyword() || token.len() != 1 || (*token.c_str() != 'f' && *token.c_str() != 'n')) {
170 // TODO(edisonn): report/warning
171 return current;
172 }
173
174 addCrossSectionInfo(startId + i, generation, offset, *token.c_str() == 'f');
175 }
176 }
177 // TODO(edisonn): it should never get here? there is no trailer?
178 return current;
179}
180
181long SkNativeParsedPDF::readTrailer(unsigned char* trailerStart, unsigned char* trailerEnd, bool storeCatalog) {
182 unsigned char* current = ignoreLine(trailerStart, trailerEnd); // TODO(edisonn): verify next keyord is "trailer" use nextObject here
183
184 SkPdfObject token;
edisonn@google.com951d6532013-07-10 23:17:31 +0000185 current = nextObject(current, trailerEnd, &token, fAllocator, NULL);
edisonn@google.com432640a2013-07-10 22:53:40 +0000186 if (!token.isDictionary()) {
187 return -1;
188 }
edisonn@google.com571c70b2013-07-10 17:09:50 +0000189 SkPdfFileTrailerDictionary* trailer = (SkPdfFileTrailerDictionary*)&token;
edisonn@google.com432640a2013-07-10 22:53:40 +0000190 if (!trailer->valid()) {
191 return -1;
192 }
edisonn@google.com571c70b2013-07-10 17:09:50 +0000193
194 if (storeCatalog) {
195 const SkPdfObject* ref = trailer->Root(NULL);
196 if (ref == NULL || !ref->isReference()) {
197 // TODO(edisonn): oops, we have to fix the corrup pdf file
198 return -1;
199 }
200 fRootCatalogRef = ref;
201 }
202
203 if (trailer->has_Prev()) {
edisonn@google.coma3356fc2013-07-10 18:20:06 +0000204 return (long)trailer->Prev(NULL);
edisonn@google.com571c70b2013-07-10 17:09:50 +0000205 }
206
207 return -1;
208}
209
210void SkNativeParsedPDF::addCrossSectionInfo(int id, int generation, int offset, bool isFreed) {
211 // TODO(edisonn): security here
212 while (fObjects.count() < id + 1) {
213 reset(fObjects.append());
214 }
215
216 fObjects[id].fOffset = offset;
217 fObjects[id].fObj = NULL;
218}
219
edisonn@google.com951d6532013-07-10 23:17:31 +0000220SkPdfObject* SkNativeParsedPDF::readObject(int id/*, int expectedGeneration*/) {
edisonn@google.com571c70b2013-07-10 17:09:50 +0000221 long startOffset = fObjects[id].fOffset;
222 //long endOffset = fObjects[id].fOffsetEnd;
223 // TODO(edisonn): use hinted endOffset
224 // TODO(edisonn): current implementation will result in a lot of memory usage
225 // to decrease memory usage, we wither need to be smart and know where objects end, and we will
226 // alocate only the chancks needed, or the tokenizer will not make copies, but then it needs to
227 // cache the results so it does not go twice on the same buffer
228 unsigned char* current = fFileContent + startOffset;
229 unsigned char* end = fFileContent + fContentLength;
230
edisonn@google.com951d6532013-07-10 23:17:31 +0000231 SkPdfNativeTokenizer tokenizer(current, end - current, fMapper, fAllocator, this);
edisonn@google.com571c70b2013-07-10 17:09:50 +0000232
233 SkPdfObject idObj;
234 SkPdfObject generationObj;
235 SkPdfObject objKeyword;
236 SkPdfObject* dict = fAllocator->allocObject();
237
edisonn@google.com951d6532013-07-10 23:17:31 +0000238 current = nextObject(current, end, &idObj, NULL, NULL);
edisonn@google.com571c70b2013-07-10 17:09:50 +0000239 if (current >= end) {
240 // TODO(edisonn): report warning/error
241 return NULL;
242 }
243
edisonn@google.com951d6532013-07-10 23:17:31 +0000244 current = nextObject(current, end, &generationObj, NULL, NULL);
edisonn@google.com571c70b2013-07-10 17:09:50 +0000245 if (current >= end) {
246 // TODO(edisonn): report warning/error
247 return NULL;
248 }
249
edisonn@google.com951d6532013-07-10 23:17:31 +0000250 current = nextObject(current, end, &objKeyword, NULL, NULL);
edisonn@google.com571c70b2013-07-10 17:09:50 +0000251 if (current >= end) {
252 // TODO(edisonn): report warning/error
253 return NULL;
254 }
255
256 if (!idObj.isInteger() || !generationObj.isInteger() || id != idObj.intValue()/* || generation != generationObj.intValue()*/) {
257 // TODO(edisonn): report warning/error
258 }
259
260 if (!objKeyword.isKeyword() || strcmp(objKeyword.c_str(), "obj") != 0) {
261 // TODO(edisonn): report warning/error
262 }
263
edisonn@google.com951d6532013-07-10 23:17:31 +0000264 current = nextObject(current, end, dict, fAllocator, this);
edisonn@google.com571c70b2013-07-10 17:09:50 +0000265
266 // TODO(edisonn): report warning/error - verify last token is endobj
267
268 return dict;
269}
270
271void SkNativeParsedPDF::fillPages(SkPdfPageTreeNodeDictionary* tree) {
272 const SkPdfArray* kids = tree->Kids(this);
273 if (kids == NULL) {
274 *fPages.append() = (SkPdfPageObjectDictionary*)tree;
275 return;
276 }
277
278 int cnt = kids->size();
279 for (int i = 0; i < cnt; i++) {
280 const SkPdfObject* obj = resolveReference(kids->objAtAIndex(i));
281 if (fMapper->mapPageObjectDictionary(obj) != kPageObjectDictionary_SkPdfObjectType) {
282 *fPages.append() = (SkPdfPageObjectDictionary*)obj;
283 } else {
284 // TODO(edisonn): verify that it is a page tree indeed
285 fillPages((SkPdfPageTreeNodeDictionary*)obj);
286 }
287 }
288}
289
290int SkNativeParsedPDF::pages() const {
291 return fPages.count();
292}
293
294SkPdfResourceDictionary* SkNativeParsedPDF::pageResources(int page) {
295 return fPages[page]->Resources(this);
296}
297
298// TODO(edisonn): Partial implemented. Move the logics directly in the code generator for inheritable and default value?
edisonn@google.com951d6532013-07-10 23:17:31 +0000299SkRect SkNativeParsedPDF::MediaBox(int page) {
edisonn@google.com571c70b2013-07-10 17:09:50 +0000300 SkPdfPageObjectDictionary* current = fPages[page];
301 while (!current->has_MediaBox() && current->has_Parent()) {
302 current = (SkPdfPageObjectDictionary*)current->Parent(this);
303 }
304 if (current) {
305 return current->MediaBox(this);
306 }
307 return SkRect::MakeEmpty();
308}
309
310// TODO(edisonn): stream or array ... ? for now only array
edisonn@google.com951d6532013-07-10 23:17:31 +0000311SkPdfNativeTokenizer* SkNativeParsedPDF::tokenizerOfPage(int page) {
edisonn@google.com571c70b2013-07-10 17:09:50 +0000312 if (fPages[page]->isContentsAStream(this)) {
313 return tokenizerOfStream(fPages[page]->getContentsAsStream(this));
314 } else {
315 // TODO(edisonn): NYI, we need to concatenate all streams in the array or make the tokenizer smart
316 // so we don't allocate new memory
317 return NULL;
318 }
319}
320
edisonn@google.com951d6532013-07-10 23:17:31 +0000321SkPdfNativeTokenizer* SkNativeParsedPDF::tokenizerOfStream(SkPdfObject* stream) {
edisonn@google.com571c70b2013-07-10 17:09:50 +0000322 if (stream == NULL) {
323 return NULL;
324 }
325
edisonn@google.com951d6532013-07-10 23:17:31 +0000326 return new SkPdfNativeTokenizer(stream, fMapper, fAllocator, this);
edisonn@google.com571c70b2013-07-10 17:09:50 +0000327}
328
329// TODO(edisonn): NYI
edisonn@google.com951d6532013-07-10 23:17:31 +0000330SkPdfNativeTokenizer* SkNativeParsedPDF::tokenizerOfBuffer(unsigned char* buffer, size_t len) {
edisonn@google.com571c70b2013-07-10 17:09:50 +0000331 // warning does not track two calls in the same buffer! the buffer is updated!
332 // make a clean copy if needed!
edisonn@google.com951d6532013-07-10 23:17:31 +0000333 return new SkPdfNativeTokenizer(buffer, len, fMapper, fAllocator, this);
edisonn@google.com571c70b2013-07-10 17:09:50 +0000334}
335
336size_t SkNativeParsedPDF::objects() const {
337 return fObjects.count();
338}
339
340SkPdfObject* SkNativeParsedPDF::object(int i) {
341 SkASSERT(!(i < 0 || i > fObjects.count()));
342
343 if (i < 0 || i > fObjects.count()) {
344 return NULL;
345 }
346
347 if (fObjects[i].fObj == NULL) {
348 // TODO(edisonn): when we read the cross reference sections, store the start of the next object
349 // and fill fOffsetEnd
350 fObjects[i].fObj = readObject(i);
351 }
352
353 return fObjects[i].fObj;
354}
355
356const SkPdfMapper* SkNativeParsedPDF::mapper() const {
357 return fMapper;
358}
359
360SkPdfReal* SkNativeParsedPDF::createReal(double value) const {
361 SkPdfObject* obj = fAllocator->allocObject();
362 SkPdfObject::makeReal(value, obj);
363 return (SkPdfReal*)obj;
364}
365
366SkPdfInteger* SkNativeParsedPDF::createInteger(int value) const {
367 SkPdfObject* obj = fAllocator->allocObject();
368 SkPdfObject::makeInteger(value, obj);
369 return (SkPdfInteger*)obj;
370}
371
372SkPdfString* SkNativeParsedPDF::createString(unsigned char* sz, size_t len) const {
373 SkPdfObject* obj = fAllocator->allocObject();
374 SkPdfObject::makeString(sz, len, obj);
375 return (SkPdfString*)obj;
376}
377
edisonn@google.com571c70b2013-07-10 17:09:50 +0000378SkPdfAllocator* SkNativeParsedPDF::allocator() const {
379 return fAllocator;
380}
381
edisonn@google.com571c70b2013-07-10 17:09:50 +0000382// TODO(edisonn): fix infinite loop if ref to itself!
383// TODO(edisonn): perf, fix refs at load, and resolve will simply return fResolvedReference?
edisonn@google.com951d6532013-07-10 23:17:31 +0000384SkPdfObject* SkNativeParsedPDF::resolveReference(const SkPdfObject* ref) {
edisonn@google.com571c70b2013-07-10 17:09:50 +0000385 if (ref && ref->isReference()) {
386 int id = ref->referenceId();
387 // TODO(edisonn): generation/updates not supported now
388 //int gen = ref->referenceGeneration();
389
390 SkASSERT(!(id < 0 || id > fObjects.count()));
391
392 if (id < 0 || id > fObjects.count()) {
393 return NULL;
394 }
395
396 // TODO(edisonn): verify id and gen expected
397
398 if (fObjects[id].fResolvedReference != NULL) {
399 return fObjects[id].fResolvedReference;
400 }
401
402 if (fObjects[id].fObj == NULL) {
403 fObjects[id].fObj = readObject(id);
404 }
405
406 if (fObjects[id].fResolvedReference == NULL) {
407 if (!fObjects[id].fObj->isReference()) {
408 fObjects[id].fResolvedReference = fObjects[id].fObj;
409 } else {
410 fObjects[id].fResolvedReference = resolveReference(fObjects[id].fObj);
411 }
412 }
413
414 return fObjects[id].fResolvedReference;
415 }
416 // TODO(edisonn): fix the mess with const, probably we need to remove it pretty much everywhere
417 return (SkPdfObject*)ref;
edisonn@google.com3aac1f92013-07-02 22:42:53 +0000418}
edisonn@google.coma5aaa792013-07-11 12:27:21 +0000419
edisonn@google.com7b328fd2013-07-11 12:53:06 +0000420size_t SkNativeParsedPDF::bytesUsed() const {
edisonn@google.coma5aaa792013-07-11 12:27:21 +0000421 return fAllocator->bytesUsed() +
422 fContentLength +
423 fObjects.count() * sizeof(PublicObjectEntry) +
424 fPages.count() * sizeof(SkPdfPageObjectDictionary*) +
425 sizeof(*this);
426}