[PDF] Refactor SkPDFFont to enable font/cmap subsetting.

Patch from Arthur Hsu, original CL: http://codereview.appspot.com/4633050/

Committed: http://code.google.com/p/skia/source/detail?r=1943
Reverted: http://code.google.com/p/skia/source/detail?r=1944

Review URL: http://codereview.appspot.com/4811049

git-svn-id: http://skia.googlecode.com/svn/trunk@1956 2bbb7eff-a529-9590-31e7-b0007b416f81
diff --git a/src/pdf/SkPDFDocument.cpp b/src/pdf/SkPDFDocument.cpp
index 71c3784..38f4f32 100644
--- a/src/pdf/SkPDFDocument.cpp
+++ b/src/pdf/SkPDFDocument.cpp
@@ -18,6 +18,7 @@
 #include "SkPDFDevice.h"
 #include "SkPDFDocument.h"
 #include "SkPDFPage.h"
+#include "SkPDFFont.h"
 #include "SkStream.h"
 
 // Add the resources, starting at firstIndex to the catalog, removing any dupes.
@@ -37,6 +38,29 @@
     }
 }
 
+static void perform_font_subsetting(SkPDFCatalog* catalog,
+                                    const SkTDArray<SkPDFPage*>& pages,
+                                    SkTDArray<SkPDFObject*>* substitutes) {
+    SkASSERT(catalog);
+    SkASSERT(substitutes);
+
+    SkPDFGlyphSetMap usage;
+    for (int i = 0; i < pages.count(); ++i) {
+        usage.merge(pages[i]->getFontGlyphUsage());
+    }
+    SkPDFGlyphSetMap::F2BIter iterator(usage);
+    SkPDFGlyphSetMap::FontGlyphSetPair* entry = iterator.next();
+    while (entry) {
+        SkPDFFont* subsetFont =
+            entry->fFont->getFontSubset(entry->fGlyphSet);
+        if (subsetFont) {
+            catalog->setSubstitute(entry->fFont, subsetFont);
+            substitutes->push(subsetFont);  // Transfer ownership to substitutes
+        }
+        entry = iterator.next();
+    }
+}
+
 SkPDFDocument::SkPDFDocument(Flags flags)
         : fXRefFileOffset(0),
           fSecondPageFirstResourceIndex(0) {
@@ -55,6 +79,7 @@
         fPageTree[i]->clear();
     fPageTree.safeUnrefAll();
     fPageResources.safeUnrefAll();
+    fSubstitutes.safeUnrefAll();
 }
 
 bool SkPDFDocument::emitPDF(SkWStream* stream) {
@@ -98,6 +123,9 @@
             }
         }
 
+        // Build font subsetting info before proceeding.
+        perform_font_subsetting(fCatalog.get(), fPages, &fSubstitutes);
+
         // Figure out the size of things and inform the catalog of file offsets.
         off_t fileOffset = headerSize();
         fileOffset += fCatalog->setFileOffset(fDocCatalog.get(), fileOffset);