blob: 9b668da498893d63e0c488cbc4fe50a1fb92373a [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);
106 SkPdfPageTreeNodeDictionary* tree = fRootCatalog->Pages(this);
107
108 fillPages(tree);
109 } else {
110 // TODO(edisonn): corrupted pdf, read it from beginning and rebuild (xref, trailer, or just reall all objects)
111 // 0 pages
112 }
edisonn@google.com571c70b2013-07-10 17:09:50 +0000113
114 // now actually read all objects if we want, or do it lazyly
115 // and resolve references?... or not ...
116}
117
118// TODO(edisonn): NYI
edisonn@google.com3aac1f92013-07-02 22:42:53 +0000119SkNativeParsedPDF::~SkNativeParsedPDF() {
edisonn@google.com571c70b2013-07-10 17:09:50 +0000120 delete[] fFileContent;
121 delete fAllocator;
122}
123
124unsigned char* SkNativeParsedPDF::readCrossReferenceSection(unsigned char* xrefStart, unsigned char* trailerEnd) {
125 unsigned char* current = ignoreLine(xrefStart, trailerEnd); // TODO(edisonn): verify next keyord is "xref", use nextObject here
126
127 SkPdfObject token;
128 while (current < trailerEnd) {
129 token.reset();
130 unsigned char* previous = current;
131 current = nextObject(current, trailerEnd, &token, NULL);
132 if (!token.isInteger()) {
133 return previous;
134 }
135
edisonn@google.coma3356fc2013-07-10 18:20:06 +0000136 int startId = (int)token.intValue();
edisonn@google.com571c70b2013-07-10 17:09:50 +0000137 token.reset();
138 current = nextObject(current, trailerEnd, &token, NULL);
139
140 if (!token.isInteger()) {
141 // TODO(edisonn): report/warning
142 return current;
143 }
144
edisonn@google.coma3356fc2013-07-10 18:20:06 +0000145 int entries = (int)token.intValue();
edisonn@google.com571c70b2013-07-10 17:09:50 +0000146
147 for (int i = 0; i < entries; i++) {
148 token.reset();
149 current = nextObject(current, trailerEnd, &token, NULL);
150 if (!token.isInteger()) {
151 // TODO(edisonn): report/warning
152 return current;
153 }
edisonn@google.coma3356fc2013-07-10 18:20:06 +0000154 int offset = (int)token.intValue();
edisonn@google.com571c70b2013-07-10 17:09:50 +0000155
156 token.reset();
157 current = nextObject(current, trailerEnd, &token, NULL);
158 if (!token.isInteger()) {
159 // TODO(edisonn): report/warning
160 return current;
161 }
edisonn@google.coma3356fc2013-07-10 18:20:06 +0000162 int generation = (int)token.intValue();
edisonn@google.com571c70b2013-07-10 17:09:50 +0000163
164 token.reset();
165 current = nextObject(current, trailerEnd, &token, NULL);
166 if (!token.isKeyword() || token.len() != 1 || (*token.c_str() != 'f' && *token.c_str() != 'n')) {
167 // TODO(edisonn): report/warning
168 return current;
169 }
170
171 addCrossSectionInfo(startId + i, generation, offset, *token.c_str() == 'f');
172 }
173 }
174 // TODO(edisonn): it should never get here? there is no trailer?
175 return current;
176}
177
178long SkNativeParsedPDF::readTrailer(unsigned char* trailerStart, unsigned char* trailerEnd, bool storeCatalog) {
179 unsigned char* current = ignoreLine(trailerStart, trailerEnd); // TODO(edisonn): verify next keyord is "trailer" use nextObject here
180
181 SkPdfObject token;
182 current = nextObject(current, trailerEnd, &token, fAllocator);
edisonn@google.com432640a2013-07-10 22:53:40 +0000183 if (!token.isDictionary()) {
184 return -1;
185 }
edisonn@google.com571c70b2013-07-10 17:09:50 +0000186 SkPdfFileTrailerDictionary* trailer = (SkPdfFileTrailerDictionary*)&token;
edisonn@google.com432640a2013-07-10 22:53:40 +0000187 if (!trailer->valid()) {
188 return -1;
189 }
edisonn@google.com571c70b2013-07-10 17:09:50 +0000190
191 if (storeCatalog) {
192 const SkPdfObject* ref = trailer->Root(NULL);
193 if (ref == NULL || !ref->isReference()) {
194 // TODO(edisonn): oops, we have to fix the corrup pdf file
195 return -1;
196 }
197 fRootCatalogRef = ref;
198 }
199
200 if (trailer->has_Prev()) {
edisonn@google.coma3356fc2013-07-10 18:20:06 +0000201 return (long)trailer->Prev(NULL);
edisonn@google.com571c70b2013-07-10 17:09:50 +0000202 }
203
204 return -1;
205}
206
207void SkNativeParsedPDF::addCrossSectionInfo(int id, int generation, int offset, bool isFreed) {
208 // TODO(edisonn): security here
209 while (fObjects.count() < id + 1) {
210 reset(fObjects.append());
211 }
212
213 fObjects[id].fOffset = offset;
214 fObjects[id].fObj = NULL;
215}
216
217SkPdfObject* SkNativeParsedPDF::readObject(int id/*, int expectedGeneration*/) const {
218 long startOffset = fObjects[id].fOffset;
219 //long endOffset = fObjects[id].fOffsetEnd;
220 // TODO(edisonn): use hinted endOffset
221 // TODO(edisonn): current implementation will result in a lot of memory usage
222 // to decrease memory usage, we wither need to be smart and know where objects end, and we will
223 // alocate only the chancks needed, or the tokenizer will not make copies, but then it needs to
224 // cache the results so it does not go twice on the same buffer
225 unsigned char* current = fFileContent + startOffset;
226 unsigned char* end = fFileContent + fContentLength;
227
228 SkPdfNativeTokenizer tokenizer(current, end - current, fMapper, fAllocator);
229
230 SkPdfObject idObj;
231 SkPdfObject generationObj;
232 SkPdfObject objKeyword;
233 SkPdfObject* dict = fAllocator->allocObject();
234
235 current = nextObject(current, end, &idObj, NULL);
236 if (current >= end) {
237 // TODO(edisonn): report warning/error
238 return NULL;
239 }
240
241 current = nextObject(current, end, &generationObj, NULL);
242 if (current >= end) {
243 // TODO(edisonn): report warning/error
244 return NULL;
245 }
246
247 current = nextObject(current, end, &objKeyword, NULL);
248 if (current >= end) {
249 // TODO(edisonn): report warning/error
250 return NULL;
251 }
252
253 if (!idObj.isInteger() || !generationObj.isInteger() || id != idObj.intValue()/* || generation != generationObj.intValue()*/) {
254 // TODO(edisonn): report warning/error
255 }
256
257 if (!objKeyword.isKeyword() || strcmp(objKeyword.c_str(), "obj") != 0) {
258 // TODO(edisonn): report warning/error
259 }
260
261 current = nextObject(current, end, dict, fAllocator);
262
263 // TODO(edisonn): report warning/error - verify last token is endobj
264
265 return dict;
266}
267
268void SkNativeParsedPDF::fillPages(SkPdfPageTreeNodeDictionary* tree) {
269 const SkPdfArray* kids = tree->Kids(this);
270 if (kids == NULL) {
271 *fPages.append() = (SkPdfPageObjectDictionary*)tree;
272 return;
273 }
274
275 int cnt = kids->size();
276 for (int i = 0; i < cnt; i++) {
277 const SkPdfObject* obj = resolveReference(kids->objAtAIndex(i));
278 if (fMapper->mapPageObjectDictionary(obj) != kPageObjectDictionary_SkPdfObjectType) {
279 *fPages.append() = (SkPdfPageObjectDictionary*)obj;
280 } else {
281 // TODO(edisonn): verify that it is a page tree indeed
282 fillPages((SkPdfPageTreeNodeDictionary*)obj);
283 }
284 }
285}
286
287int SkNativeParsedPDF::pages() const {
288 return fPages.count();
289}
290
291SkPdfResourceDictionary* SkNativeParsedPDF::pageResources(int page) {
292 return fPages[page]->Resources(this);
293}
294
295// TODO(edisonn): Partial implemented. Move the logics directly in the code generator for inheritable and default value?
296SkRect SkNativeParsedPDF::MediaBox(int page) const {
297 SkPdfPageObjectDictionary* current = fPages[page];
298 while (!current->has_MediaBox() && current->has_Parent()) {
299 current = (SkPdfPageObjectDictionary*)current->Parent(this);
300 }
301 if (current) {
302 return current->MediaBox(this);
303 }
304 return SkRect::MakeEmpty();
305}
306
307// TODO(edisonn): stream or array ... ? for now only array
308SkPdfNativeTokenizer* SkNativeParsedPDF::tokenizerOfPage(int page) const {
309 if (fPages[page]->isContentsAStream(this)) {
310 return tokenizerOfStream(fPages[page]->getContentsAsStream(this));
311 } else {
312 // TODO(edisonn): NYI, we need to concatenate all streams in the array or make the tokenizer smart
313 // so we don't allocate new memory
314 return NULL;
315 }
316}
317
318SkPdfNativeTokenizer* SkNativeParsedPDF::tokenizerOfStream(SkPdfObject* stream) const {
319 if (stream == NULL) {
320 return NULL;
321 }
322
323 return new SkPdfNativeTokenizer(stream, fMapper, fAllocator);
324}
325
326// TODO(edisonn): NYI
327SkPdfNativeTokenizer* SkNativeParsedPDF::tokenizerOfBuffer(unsigned char* buffer, size_t len) const {
328 // warning does not track two calls in the same buffer! the buffer is updated!
329 // make a clean copy if needed!
330 return new SkPdfNativeTokenizer(buffer, len, fMapper, fAllocator);
331}
332
333size_t SkNativeParsedPDF::objects() const {
334 return fObjects.count();
335}
336
337SkPdfObject* SkNativeParsedPDF::object(int i) {
338 SkASSERT(!(i < 0 || i > fObjects.count()));
339
340 if (i < 0 || i > fObjects.count()) {
341 return NULL;
342 }
343
344 if (fObjects[i].fObj == NULL) {
345 // TODO(edisonn): when we read the cross reference sections, store the start of the next object
346 // and fill fOffsetEnd
347 fObjects[i].fObj = readObject(i);
348 }
349
350 return fObjects[i].fObj;
351}
352
353const SkPdfMapper* SkNativeParsedPDF::mapper() const {
354 return fMapper;
355}
356
357SkPdfReal* SkNativeParsedPDF::createReal(double value) const {
358 SkPdfObject* obj = fAllocator->allocObject();
359 SkPdfObject::makeReal(value, obj);
360 return (SkPdfReal*)obj;
361}
362
363SkPdfInteger* SkNativeParsedPDF::createInteger(int value) const {
364 SkPdfObject* obj = fAllocator->allocObject();
365 SkPdfObject::makeInteger(value, obj);
366 return (SkPdfInteger*)obj;
367}
368
369SkPdfString* SkNativeParsedPDF::createString(unsigned char* sz, size_t len) const {
370 SkPdfObject* obj = fAllocator->allocObject();
371 SkPdfObject::makeString(sz, len, obj);
372 return (SkPdfString*)obj;
373}
374
edisonn@google.com571c70b2013-07-10 17:09:50 +0000375SkPdfAllocator* SkNativeParsedPDF::allocator() const {
376 return fAllocator;
377}
378
379SkPdfObject* SkNativeParsedPDF::resolveReference(SkPdfObject* ref) const {
380 return (SkPdfObject*)resolveReference((const SkPdfObject*)ref);
381}
382
383// TODO(edisonn): fix infinite loop if ref to itself!
384// TODO(edisonn): perf, fix refs at load, and resolve will simply return fResolvedReference?
385SkPdfObject* SkNativeParsedPDF::resolveReference(const SkPdfObject* ref) const {
386 if (ref && ref->isReference()) {
387 int id = ref->referenceId();
388 // TODO(edisonn): generation/updates not supported now
389 //int gen = ref->referenceGeneration();
390
391 SkASSERT(!(id < 0 || id > fObjects.count()));
392
393 if (id < 0 || id > fObjects.count()) {
394 return NULL;
395 }
396
397 // TODO(edisonn): verify id and gen expected
398
399 if (fObjects[id].fResolvedReference != NULL) {
400 return fObjects[id].fResolvedReference;
401 }
402
403 if (fObjects[id].fObj == NULL) {
404 fObjects[id].fObj = readObject(id);
405 }
406
407 if (fObjects[id].fResolvedReference == NULL) {
408 if (!fObjects[id].fObj->isReference()) {
409 fObjects[id].fResolvedReference = fObjects[id].fObj;
410 } else {
411 fObjects[id].fResolvedReference = resolveReference(fObjects[id].fObj);
412 }
413 }
414
415 return fObjects[id].fResolvedReference;
416 }
417 // TODO(edisonn): fix the mess with const, probably we need to remove it pretty much everywhere
418 return (SkPdfObject*)ref;
edisonn@google.com3aac1f92013-07-02 22:42:53 +0000419}