C++11 override should now be supported by all of {bots,Chrome,Android,Mozilla}
[platform/upstream/libSkiaSharp.git] / src / doc / SkDocument_PDF.cpp
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 "SkDocument.h"
9 #include "SkPDFCanon.h"
10 #include "SkPDFCatalog.h"
11 #include "SkPDFDevice.h"
12 #include "SkPDFFont.h"
13 #include "SkPDFResourceDict.h"
14 #include "SkPDFStream.h"
15 #include "SkPDFTypes.h"
16 #include "SkStream.h"
17
18 static void emit_pdf_header(SkWStream* stream) {
19     stream->writeText("%PDF-1.4\n%");
20     // The PDF spec recommends including a comment with four bytes, all
21     // with their high bits set.  This is "Skia" with the high bits set.
22     stream->write32(0xD3EBE9E1);
23     stream->writeText("\n");
24 }
25
26 static void emit_pdf_footer(SkWStream* stream,
27                             SkPDFCatalog* catalog,
28                             SkPDFObject* docCatalog,
29                             int64_t objCount,
30                             int32_t xRefFileOffset) {
31     SkPDFDict trailerDict;
32     // TODO(vandebo): Linearized format will take a Prev entry too.
33     // TODO(vandebo): PDF/A requires an ID entry.
34     trailerDict.insertInt("Size", int(objCount));
35     trailerDict.insert("Root", new SkPDFObjRef(docCatalog))->unref();
36
37     stream->writeText("trailer\n");
38     trailerDict.emitObject(stream, catalog);
39     stream->writeText("\nstartxref\n");
40     stream->writeBigDecAsText(xRefFileOffset);
41     stream->writeText("\n%%EOF");
42 }
43
44 static void perform_font_subsetting(
45         const SkTDArray<const SkPDFDevice*>& pageDevices,
46         SkPDFCatalog* catalog) {
47     SkASSERT(catalog);
48
49     SkPDFGlyphSetMap usage;
50     for (int i = 0; i < pageDevices.count(); ++i) {
51         usage.merge(pageDevices[i]->getFontGlyphUsage());
52     }
53     SkPDFGlyphSetMap::F2BIter iterator(usage);
54     const SkPDFGlyphSetMap::FontGlyphSetPair* entry = iterator.next();
55     while (entry) {
56         SkAutoTUnref<SkPDFFont> subsetFont(
57                 entry->fFont->getFontSubset(entry->fGlyphSet));
58         if (subsetFont) {
59             catalog->setSubstitute(entry->fFont, subsetFont.get());
60         }
61         entry = iterator.next();
62     }
63 }
64
65 static SkPDFDict* create_pdf_page(const SkPDFDevice* pageDevice) {
66     SkAutoTUnref<SkPDFDict> page(SkNEW_ARGS(SkPDFDict, ("Page")));
67     SkAutoTUnref<SkPDFResourceDict> deviceResourceDict(
68             pageDevice->createResourceDict());
69     page->insert("Resources", deviceResourceDict.get());
70
71     SkAutoTUnref<SkPDFArray> mediaBox(pageDevice->copyMediaBox());
72     page->insert("MediaBox", mediaBox.get());
73
74     SkPDFArray* annots = pageDevice->getAnnotations();
75     if (annots && annots->size() > 0) {
76         page->insert("Annots", annots);
77     }
78
79     SkAutoTDelete<SkStreamAsset> content(pageDevice->content());
80     SkAutoTUnref<SkPDFStream> contentStream(
81             SkNEW_ARGS(SkPDFStream, (content.get())));
82     page->insert("Contents", new SkPDFObjRef(contentStream.get()))->unref();
83     return page.detach();
84 }
85
86 static void generate_page_tree(const SkTDArray<SkPDFDict*>& pages,
87                                SkTDArray<SkPDFDict*>* pageTree,
88                                SkPDFDict** rootNode) {
89     // PDF wants a tree describing all the pages in the document.  We arbitrary
90     // choose 8 (kNodeSize) as the number of allowed children.  The internal
91     // nodes have type "Pages" with an array of children, a parent pointer, and
92     // the number of leaves below the node as "Count."  The leaves are passed
93     // into the method, have type "Page" and need a parent pointer. This method
94     // builds the tree bottom up, skipping internal nodes that would have only
95     // one child.
96     static const int kNodeSize = 8;
97
98     SkAutoTUnref<SkPDFName> kidsName(new SkPDFName("Kids"));
99     SkAutoTUnref<SkPDFName> countName(new SkPDFName("Count"));
100     SkAutoTUnref<SkPDFName> parentName(new SkPDFName("Parent"));
101
102     // curNodes takes a reference to its items, which it passes to pageTree.
103     SkTDArray<SkPDFDict*> curNodes;
104     curNodes.setReserve(pages.count());
105     for (int i = 0; i < pages.count(); i++) {
106         SkSafeRef(pages[i]);
107         curNodes.push(pages[i]);
108     }
109
110     // nextRoundNodes passes its references to nodes on to curNodes.
111     SkTDArray<SkPDFDict*> nextRoundNodes;
112     nextRoundNodes.setReserve((pages.count() + kNodeSize - 1)/kNodeSize);
113
114     int treeCapacity = kNodeSize;
115     do {
116         for (int i = 0; i < curNodes.count(); ) {
117             if (i > 0 && i + 1 == curNodes.count()) {
118                 nextRoundNodes.push(curNodes[i]);
119                 break;
120             }
121
122             SkPDFDict* newNode = new SkPDFDict("Pages");
123             SkAutoTUnref<SkPDFObjRef> newNodeRef(new SkPDFObjRef(newNode));
124
125             SkAutoTUnref<SkPDFArray> kids(new SkPDFArray);
126             kids->reserve(kNodeSize);
127
128             int count = 0;
129             for (; i < curNodes.count() && count < kNodeSize; i++, count++) {
130                 curNodes[i]->insert(parentName.get(), newNodeRef.get());
131                 kids->append(new SkPDFObjRef(curNodes[i]))->unref();
132
133                 // TODO(vandebo): put the objects in strict access order.
134                 // Probably doesn't matter because they are so small.
135                 if (curNodes[i] != pages[0]) {
136                     pageTree->push(curNodes[i]);  // Transfer reference.
137                 } else {
138                     SkSafeUnref(curNodes[i]);
139                 }
140             }
141
142             // treeCapacity is the number of leaf nodes possible for the
143             // current set of subtrees being generated. (i.e. 8, 64, 512, ...).
144             // It is hard to count the number of leaf nodes in the current
145             // subtree. However, by construction, we know that unless it's the
146             // last subtree for the current depth, the leaf count will be
147             // treeCapacity, otherwise it's what ever is left over after
148             // consuming treeCapacity chunks.
149             int pageCount = treeCapacity;
150             if (i == curNodes.count()) {
151                 pageCount = ((pages.count() - 1) % treeCapacity) + 1;
152             }
153             newNode->insert(countName.get(), new SkPDFInt(pageCount))->unref();
154             newNode->insert(kidsName.get(), kids.get());
155             nextRoundNodes.push(newNode);  // Transfer reference.
156         }
157
158         curNodes = nextRoundNodes;
159         nextRoundNodes.rewind();
160         treeCapacity *= kNodeSize;
161     } while (curNodes.count() > 1);
162
163     pageTree->push(curNodes[0]);  // Transfer reference.
164     if (rootNode) {
165         *rootNode = curNodes[0];
166     }
167 }
168
169 static bool emit_pdf_document(const SkTDArray<const SkPDFDevice*>& pageDevices,
170                               SkWStream* stream) {
171     if (pageDevices.isEmpty()) {
172         return false;
173     }
174
175     SkTDArray<SkPDFDict*> pages;
176     SkAutoTUnref<SkPDFDict> dests(SkNEW(SkPDFDict));
177
178     for (int i = 0; i < pageDevices.count(); i++) {
179         SkASSERT(pageDevices[i]);
180         SkASSERT(i == 0 ||
181                  pageDevices[i - 1]->getCanon() == pageDevices[i]->getCanon());
182         SkAutoTUnref<SkPDFDict> page(create_pdf_page(pageDevices[i]));
183         pageDevices[i]->appendDestinations(dests, page.get());
184         pages.push(page.detach());
185     }
186     SkPDFCatalog catalog;
187
188     SkTDArray<SkPDFDict*> pageTree;
189     SkAutoTUnref<SkPDFDict> docCatalog(SkNEW_ARGS(SkPDFDict, ("Catalog")));
190
191     SkPDFDict* pageTreeRoot;
192     generate_page_tree(pages, &pageTree, &pageTreeRoot);
193
194     docCatalog->insert("Pages", new SkPDFObjRef(pageTreeRoot))->unref();
195
196     /* TODO(vandebo): output intent
197     SkAutoTUnref<SkPDFDict> outputIntent = new SkPDFDict("OutputIntent");
198     outputIntent->insert("S", new SkPDFName("GTS_PDFA1"))->unref();
199     outputIntent->insert("OutputConditionIdentifier",
200                          new SkPDFString("sRGB"))->unref();
201     SkAutoTUnref<SkPDFArray> intentArray = new SkPDFArray;
202     intentArray->append(outputIntent.get());
203     docCatalog->insert("OutputIntent", intentArray.get());
204     */
205
206     if (dests->size() > 0) {
207         docCatalog->insert("Dests", SkNEW_ARGS(SkPDFObjRef, (dests.get())))
208                 ->unref();
209     }
210
211     // Build font subsetting info before proceeding.
212     perform_font_subsetting(pageDevices, &catalog);
213
214     if (catalog.addObject(docCatalog.get())) {
215         docCatalog->addResources(&catalog);
216     }
217     size_t baseOffset = SkToOffT(stream->bytesWritten());
218     emit_pdf_header(stream);
219     SkTDArray<int32_t> offsets;
220     for (int i = 0; i < catalog.objects().count(); ++i) {
221         SkPDFObject* object = catalog.objects()[i];
222         offsets.push(SkToS32(stream->bytesWritten() - baseOffset));
223         SkASSERT(object == catalog.getSubstituteObject(object));
224         SkASSERT(catalog.getObjectNumber(object) == i + 1);
225         stream->writeDecAsText(i + 1);
226         stream->writeText(" 0 obj\n");  // Generation number is always 0.
227         object->emitObject(stream, &catalog);
228         stream->writeText("\nendobj\n");
229     }
230     int32_t xRefFileOffset = SkToS32(stream->bytesWritten() - baseOffset);
231
232     int32_t objCount = SkToS32(offsets.count() + 1);
233
234     stream->writeText("xref\n0 ");
235     stream->writeDecAsText(objCount + 1);
236     stream->writeText("\n0000000000 65535 f \n");
237     for (int i = 0; i < offsets.count(); i++) {
238         SkASSERT(offsets[i] > 0);
239         stream->writeBigDecAsText(offsets[i], 10);
240         stream->writeText(" 00000 n \n");
241     }
242     emit_pdf_footer(stream, &catalog, docCatalog.get(), objCount,
243                     xRefFileOffset);
244
245     // The page tree has both child and parent pointers, so it creates a
246     // reference cycle.  We must clear that cycle to properly reclaim memory.
247     for (int i = 0; i < pageTree.count(); i++) {
248         pageTree[i]->clear();
249     }
250     pageTree.safeUnrefAll();
251     pages.unrefAll();
252     return true;
253 }
254
255 #if 0
256 // TODO(halcanary): expose notEmbeddableCount in SkDocument
257 void GetCountOfFontTypes(
258         const SkTDArray<SkPDFDevice*>& pageDevices,
259         int counts[SkAdvancedTypefaceMetrics::kOther_Font + 1],
260         int* notSubsettableCount,
261         int* notEmbeddableCount) {
262     sk_bzero(counts, sizeof(int) *
263                      (SkAdvancedTypefaceMetrics::kOther_Font + 1));
264     SkTDArray<SkFontID> seenFonts;
265     int notSubsettable = 0;
266     int notEmbeddable = 0;
267
268     for (int pageNumber = 0; pageNumber < pageDevices.count(); pageNumber++) {
269         const SkTDArray<SkPDFFont*>& fontResources =
270                 pageDevices[pageNumber]->getFontResources();
271         for (int font = 0; font < fontResources.count(); font++) {
272             SkFontID fontID = fontResources[font]->typeface()->uniqueID();
273             if (seenFonts.find(fontID) == -1) {
274                 counts[fontResources[font]->getType()]++;
275                 seenFonts.push(fontID);
276                 if (!fontResources[font]->canSubset()) {
277                     notSubsettable++;
278                 }
279                 if (!fontResources[font]->canEmbed()) {
280                     notEmbeddable++;
281                 }
282             }
283         }
284     }
285     if (notSubsettableCount) {
286         *notSubsettableCount = notSubsettable;
287
288     }
289     if (notEmbeddableCount) {
290         *notEmbeddableCount = notEmbeddable;
291     }
292 }
293 #endif
294 ////////////////////////////////////////////////////////////////////////////////
295
296 namespace {
297 class SkDocument_PDF : public SkDocument {
298 public:
299     SkDocument_PDF(SkWStream* stream,
300                    void (*doneProc)(SkWStream*, bool),
301                    SkScalar rasterDpi)
302         : SkDocument(stream, doneProc)
303         , fRasterDpi(rasterDpi) {}
304
305     virtual ~SkDocument_PDF() {
306         // subclasses must call close() in their destructors
307         this->close();
308     }
309
310 protected:
311     virtual SkCanvas* onBeginPage(SkScalar width, SkScalar height,
312                                   const SkRect& trimBox) override {
313         SkASSERT(!fCanvas.get());
314
315         SkISize pageSize = SkISize::Make(
316                 SkScalarRoundToInt(width), SkScalarRoundToInt(height));
317         SkAutoTUnref<SkPDFDevice> device(
318                 SkPDFDevice::Create(pageSize, fRasterDpi, &fCanon));
319         fCanvas.reset(SkNEW_ARGS(SkCanvas, (device.get())));
320         fPageDevices.push(device.detach());
321         fCanvas->clipRect(trimBox);
322         fCanvas->translate(trimBox.x(), trimBox.y());
323         return fCanvas.get();
324     }
325
326     void onEndPage() override {
327         SkASSERT(fCanvas.get());
328         fCanvas->flush();
329         fCanvas.reset(NULL);
330     }
331
332     bool onClose(SkWStream* stream) override {
333         SkASSERT(!fCanvas.get());
334
335         bool success = emit_pdf_document(fPageDevices, stream);
336         fPageDevices.unrefAll();
337         fCanon.reset();
338         return success;
339     }
340
341     void onAbort() override {
342         fPageDevices.unrefAll();
343         fCanon.reset();
344     }
345
346 private:
347     SkPDFCanon fCanon;
348     SkTDArray<const SkPDFDevice*> fPageDevices;
349     SkAutoTUnref<SkCanvas> fCanvas;
350     SkScalar fRasterDpi;
351 };
352 }  // namespace
353 ///////////////////////////////////////////////////////////////////////////////
354
355 SkDocument* SkDocument::CreatePDF(SkWStream* stream, SkScalar dpi) {
356     return stream ? SkNEW_ARGS(SkDocument_PDF, (stream, NULL, dpi)) : NULL;
357 }
358
359 SkDocument* SkDocument::CreatePDF(const char path[], SkScalar dpi) {
360     SkFILEWStream* stream = SkNEW_ARGS(SkFILEWStream, (path));
361     if (!stream->isValid()) {
362         SkDELETE(stream);
363         return NULL;
364     }
365     auto delete_wstream = [](SkWStream* stream, bool) { SkDELETE(stream); };
366     return SkNEW_ARGS(SkDocument_PDF, (stream, delete_wstream, dpi));
367 }