PdfRenderer.cpp revision ed6b9dff563c5e22f040ff37e12c0d771e0478ae
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "jni.h"
18#include "JNIHelp.h"
19#include "GraphicsJNI.h"
20#include "SkBitmap.h"
21#include "SkMatrix.h"
22#include "fpdfview.h"
23
24#pragma GCC diagnostic push
25#pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor"
26#include "fsdk_rendercontext.h"
27#pragma GCC diagnostic pop
28
29#include "core_jni_helpers.h"
30#include <vector>
31#include <utils/Log.h>
32#include <unistd.h>
33#include <sys/types.h>
34#include <unistd.h>
35
36namespace android {
37
38static const int RENDER_MODE_FOR_DISPLAY = 1;
39static const int RENDER_MODE_FOR_PRINT = 2;
40
41static struct {
42    jfieldID x;
43    jfieldID y;
44} gPointClassInfo;
45
46static Mutex sLock;
47
48static int sUnmatchedInitRequestCount = 0;
49
50static void initializeLibraryIfNeeded() {
51    Mutex::Autolock _l(sLock);
52    if (sUnmatchedInitRequestCount == 0) {
53        FPDF_InitLibrary(NULL);
54    }
55    sUnmatchedInitRequestCount++;
56}
57
58static void destroyLibraryIfNeeded() {
59    Mutex::Autolock _l(sLock);
60    sUnmatchedInitRequestCount--;
61    if (sUnmatchedInitRequestCount == 0) {
62       FPDF_DestroyLibrary();
63    }
64}
65
66static int getBlock(void* param, unsigned long position, unsigned char* outBuffer,
67        unsigned long size) {
68    const int fd = reinterpret_cast<intptr_t>(param);
69    const int readCount = pread(fd, outBuffer, size, position);
70    if (readCount < 0) {
71        ALOGE("Cannot read from file descriptor. Error:%d", errno);
72        return 0;
73    }
74    return 1;
75}
76
77static jlong nativeCreate(JNIEnv* env, jclass thiz, jint fd, jlong size) {
78    initializeLibraryIfNeeded();
79
80    FPDF_FILEACCESS loader;
81    loader.m_FileLen = size;
82    loader.m_Param = reinterpret_cast<void*>(intptr_t(fd));
83    loader.m_GetBlock = &getBlock;
84
85    FPDF_DOCUMENT document = FPDF_LoadCustomDocument(&loader, NULL);
86
87    if (!document) {
88        const long error = FPDF_GetLastError();
89        jniThrowExceptionFmt(env, "java/io/IOException",
90                "cannot create document. Error: %ld", error);
91        destroyLibraryIfNeeded();
92        return -1;
93    }
94
95    return reinterpret_cast<jlong>(document);
96}
97
98static jlong nativeOpenPageAndGetSize(JNIEnv* env, jclass thiz, jlong documentPtr,
99        jint pageIndex, jobject outSize) {
100    FPDF_DOCUMENT document = reinterpret_cast<FPDF_DOCUMENT>(documentPtr);
101
102    FPDF_PAGE page = FPDF_LoadPage(document, pageIndex);
103
104    if (!page) {
105        jniThrowException(env, "java/lang/IllegalStateException",
106                "cannot load page");
107        return -1;
108    }
109
110    double width = 0;
111    double height = 0;
112
113    const int result = FPDF_GetPageSizeByIndex(document, pageIndex, &width, &height);
114
115    if (!result) {
116        jniThrowException(env, "java/lang/IllegalStateException",
117                    "cannot get page size");
118        return -1;
119    }
120
121    env->SetIntField(outSize, gPointClassInfo.x, width);
122    env->SetIntField(outSize, gPointClassInfo.y, height);
123
124    return reinterpret_cast<jlong>(page);
125}
126
127static void nativeClosePage(JNIEnv* env, jclass thiz, jlong pagePtr) {
128    FPDF_PAGE page = reinterpret_cast<FPDF_PAGE>(pagePtr);
129    FPDF_ClosePage(page);
130}
131
132static void nativeClose(JNIEnv* env, jclass thiz, jlong documentPtr) {
133    FPDF_DOCUMENT document = reinterpret_cast<FPDF_DOCUMENT>(documentPtr);
134    FPDF_CloseDocument(document);
135    destroyLibraryIfNeeded();
136}
137
138static jint nativeGetPageCount(JNIEnv* env, jclass thiz, jlong documentPtr) {
139    FPDF_DOCUMENT document = reinterpret_cast<FPDF_DOCUMENT>(documentPtr);
140    return FPDF_GetPageCount(document);
141}
142
143static jboolean nativeScaleForPrinting(JNIEnv* env, jclass thiz, jlong documentPtr) {
144    FPDF_DOCUMENT document = reinterpret_cast<FPDF_DOCUMENT>(documentPtr);
145    return FPDF_VIEWERREF_GetPrintScaling(document);
146}
147
148static void DropContext(void* data) {
149    delete (CRenderContext*) data;
150}
151
152static void renderPageBitmap(FPDF_BITMAP bitmap, FPDF_PAGE page, int destLeft, int destTop,
153        int destRight, int destBottom, SkMatrix* transform, int flags) {
154    // Note: this code ignores the currently unused RENDER_NO_NATIVETEXT,
155    // FPDF_RENDER_LIMITEDIMAGECACHE, FPDF_RENDER_FORCEHALFTONE, FPDF_GRAYSCALE,
156    // and FPDF_ANNOT flags. To add support for that refer to FPDF_RenderPage_Retail
157    // in fpdfview.cpp
158
159    CRenderContext* pContext = FX_NEW CRenderContext;
160
161    CPDF_Page* pPage = (CPDF_Page*) page;
162    pPage->SetPrivateData((void*) 1, pContext, DropContext);
163
164    CFX_FxgeDevice* fxgeDevice = FX_NEW CFX_FxgeDevice;
165    pContext->m_pDevice = fxgeDevice;
166
167    // Reverse the bytes (last argument TRUE) since the Android
168    // format is ARGB while the renderer uses BGRA internally.
169    fxgeDevice->Attach((CFX_DIBitmap*) bitmap, 0, TRUE);
170
171    CPDF_RenderOptions* renderOptions = pContext->m_pOptions;
172
173    if (!renderOptions) {
174        renderOptions = FX_NEW CPDF_RenderOptions;
175        pContext->m_pOptions = renderOptions;
176    }
177
178    if (flags & FPDF_LCD_TEXT) {
179        renderOptions->m_Flags |= RENDER_CLEARTYPE;
180    } else {
181        renderOptions->m_Flags &= ~RENDER_CLEARTYPE;
182    }
183
184    const CPDF_OCContext::UsageType usage = (flags & FPDF_PRINTING)
185            ? CPDF_OCContext::Print : CPDF_OCContext::View;
186
187    renderOptions->m_AddFlags = flags >> 8;
188    renderOptions->m_pOCContext = new CPDF_OCContext(pPage->m_pDocument, usage);
189
190    fxgeDevice->SaveState();
191
192    FX_RECT clip;
193    clip.left = destLeft;
194    clip.right = destRight;
195    clip.top = destTop;
196    clip.bottom = destBottom;
197    fxgeDevice->SetClip_Rect(&clip);
198
199    CPDF_RenderContext* pageContext = FX_NEW CPDF_RenderContext;
200    pContext->m_pContext = pageContext;
201    pageContext->Create(pPage);
202
203    CFX_AffineMatrix matrix;
204    if (!transform) {
205        pPage->GetDisplayMatrix(matrix, destLeft, destTop, destRight - destLeft,
206                destBottom - destTop, 0);
207    } else {
208        // PDF's coordinate system origin is left-bottom while
209        // in graphics it is the top-left, so remap the origin.
210        matrix.Set(1, 0, 0, -1, 0, pPage->GetPageHeight());
211
212        SkScalar transformValues[6];
213        transform->asAffine(transformValues);
214
215        matrix.Concat(transformValues[SkMatrix::kAScaleX], transformValues[SkMatrix::kASkewY],
216                transformValues[SkMatrix::kASkewX], transformValues[SkMatrix::kAScaleY],
217                transformValues[SkMatrix::kATransX], transformValues[SkMatrix::kATransY]);
218    }
219    pageContext->AppendObjectList(pPage, &matrix);
220
221    pContext->m_pRenderer = FX_NEW CPDF_ProgressiveRenderer;
222    pContext->m_pRenderer->Start(pageContext, fxgeDevice, renderOptions, NULL);
223
224    fxgeDevice->RestoreState();
225
226    pPage->RemovePrivateData((void*) 1);
227
228    delete pContext;
229}
230
231static void nativeRenderPage(JNIEnv* env, jclass thiz, jlong documentPtr, jlong pagePtr,
232        jlong bitmapPtr, jint destLeft, jint destTop, jint destRight, jint destBottom,
233        jlong matrixPtr, jint renderMode) {
234
235    FPDF_PAGE page = reinterpret_cast<FPDF_PAGE>(pagePtr);
236    SkBitmap* skBitmap = reinterpret_cast<SkBitmap*>(bitmapPtr);
237    SkMatrix* skMatrix = reinterpret_cast<SkMatrix*>(matrixPtr);
238
239    skBitmap->lockPixels();
240
241    const int stride = skBitmap->width() * 4;
242
243    FPDF_BITMAP bitmap = FPDFBitmap_CreateEx(skBitmap->width(), skBitmap->height(),
244            FPDFBitmap_BGRA, skBitmap->getPixels(), stride);
245
246    if (!bitmap) {
247        ALOGE("Erorr creating bitmap");
248        return;
249    }
250
251    int renderFlags = 0;
252    if (renderMode == RENDER_MODE_FOR_DISPLAY) {
253        renderFlags |= FPDF_LCD_TEXT;
254    } else if (renderMode == RENDER_MODE_FOR_PRINT) {
255        renderFlags |= FPDF_PRINTING;
256    }
257
258    renderPageBitmap(bitmap, page, destLeft, destTop, destRight,
259            destBottom, skMatrix, renderFlags);
260
261    skBitmap->notifyPixelsChanged();
262    skBitmap->unlockPixels();
263}
264
265static JNINativeMethod gPdfRenderer_Methods[] = {
266    {"nativeCreate", "(IJ)J", (void*) nativeCreate},
267    {"nativeClose", "(J)V", (void*) nativeClose},
268    {"nativeGetPageCount", "(J)I", (void*) nativeGetPageCount},
269    {"nativeScaleForPrinting", "(J)Z", (void*) nativeScaleForPrinting},
270    {"nativeRenderPage", "(JJJIIIIJI)V", (void*) nativeRenderPage},
271    {"nativeOpenPageAndGetSize", "(JILandroid/graphics/Point;)J", (void*) nativeOpenPageAndGetSize},
272    {"nativeClosePage", "(J)V", (void*) nativeClosePage}
273};
274
275int register_android_graphics_pdf_PdfRenderer(JNIEnv* env) {
276    int result = RegisterMethodsOrDie(
277            env, "android/graphics/pdf/PdfRenderer", gPdfRenderer_Methods,
278            NELEM(gPdfRenderer_Methods));
279
280    jclass clazz = FindClassOrDie(env, "android/graphics/Point");
281    gPointClassInfo.x = GetFieldIDOrDie(env, clazz, "x", "I");
282    gPointClassInfo.y = GetFieldIDOrDie(env, clazz, "y", "I");
283
284    return result;
285};
286
287};
288