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
46// See PdfEditor.cpp
47extern Mutex sPdfiumLock;
48extern int sUnmatchedPdfiumInitRequestCount;
49
50static void initializeLibraryIfNeeded() {
51    Mutex::Autolock _l(sPdfiumLock);
52    if (sUnmatchedPdfiumInitRequestCount == 0) {
53        FPDF_InitLibrary();
54    }
55    sUnmatchedPdfiumInitRequestCount++;
56}
57
58static void destroyLibraryIfNeeded() {
59    Mutex::Autolock _l(sPdfiumLock);
60    sUnmatchedPdfiumInitRequestCount--;
61    if (sUnmatchedPdfiumInitRequestCount == 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        switch (error) {
90            case FPDF_ERR_PASSWORD:
91            case FPDF_ERR_SECURITY: {
92                jniThrowExceptionFmt(env, "java/lang/SecurityException",
93                        "cannot create document. Error: %ld", error);
94            } break;
95            default: {
96                jniThrowExceptionFmt(env, "java/io/IOException",
97                        "cannot create document. Error: %ld", error);
98            } break;
99        }
100        destroyLibraryIfNeeded();
101        return -1;
102    }
103
104    return reinterpret_cast<jlong>(document);
105}
106
107static jlong nativeOpenPageAndGetSize(JNIEnv* env, jclass thiz, jlong documentPtr,
108        jint pageIndex, jobject outSize) {
109    FPDF_DOCUMENT document = reinterpret_cast<FPDF_DOCUMENT>(documentPtr);
110
111    FPDF_PAGE page = FPDF_LoadPage(document, pageIndex);
112
113    if (!page) {
114        jniThrowException(env, "java/lang/IllegalStateException",
115                "cannot load page");
116        return -1;
117    }
118
119    double width = 0;
120    double height = 0;
121
122    const int result = FPDF_GetPageSizeByIndex(document, pageIndex, &width, &height);
123
124    if (!result) {
125        jniThrowException(env, "java/lang/IllegalStateException",
126                    "cannot get page size");
127        return -1;
128    }
129
130    env->SetIntField(outSize, gPointClassInfo.x, width);
131    env->SetIntField(outSize, gPointClassInfo.y, height);
132
133    return reinterpret_cast<jlong>(page);
134}
135
136static void nativeClosePage(JNIEnv* env, jclass thiz, jlong pagePtr) {
137    FPDF_PAGE page = reinterpret_cast<FPDF_PAGE>(pagePtr);
138    FPDF_ClosePage(page);
139}
140
141static void nativeClose(JNIEnv* env, jclass thiz, jlong documentPtr) {
142    FPDF_DOCUMENT document = reinterpret_cast<FPDF_DOCUMENT>(documentPtr);
143    FPDF_CloseDocument(document);
144    destroyLibraryIfNeeded();
145}
146
147static jint nativeGetPageCount(JNIEnv* env, jclass thiz, jlong documentPtr) {
148    FPDF_DOCUMENT document = reinterpret_cast<FPDF_DOCUMENT>(documentPtr);
149    return FPDF_GetPageCount(document);
150}
151
152static jboolean nativeScaleForPrinting(JNIEnv* env, jclass thiz, jlong documentPtr) {
153    FPDF_DOCUMENT document = reinterpret_cast<FPDF_DOCUMENT>(documentPtr);
154    return FPDF_VIEWERREF_GetPrintScaling(document);
155}
156
157static void DropContext(void* data) {
158    delete (CRenderContext*) data;
159}
160
161static void renderPageBitmap(FPDF_BITMAP bitmap, FPDF_PAGE page, int destLeft, int destTop,
162        int destRight, int destBottom, SkMatrix* transform, int flags) {
163    // Note: this code ignores the currently unused RENDER_NO_NATIVETEXT,
164    // FPDF_RENDER_LIMITEDIMAGECACHE, FPDF_RENDER_FORCEHALFTONE, FPDF_GRAYSCALE,
165    // and FPDF_ANNOT flags. To add support for that refer to FPDF_RenderPage_Retail
166    // in fpdfview.cpp
167
168    CRenderContext* pContext = new CRenderContext;
169
170    CPDF_Page* pPage = (CPDF_Page*) page;
171    pPage->SetPrivateData((void*) 1, pContext, DropContext);
172
173    CFX_FxgeDevice* fxgeDevice = new CFX_FxgeDevice;
174    pContext->m_pDevice = fxgeDevice;
175
176    // Reverse the bytes (last argument TRUE) since the Android
177    // format is ARGB while the renderer uses BGRA internally.
178    fxgeDevice->Attach((CFX_DIBitmap*) bitmap, 0, TRUE);
179
180    CPDF_RenderOptions* renderOptions = pContext->m_pOptions;
181
182    if (!renderOptions) {
183        renderOptions = new CPDF_RenderOptions;
184        pContext->m_pOptions = renderOptions;
185    }
186
187    if (flags & FPDF_LCD_TEXT) {
188        renderOptions->m_Flags |= RENDER_CLEARTYPE;
189    } else {
190        renderOptions->m_Flags &= ~RENDER_CLEARTYPE;
191    }
192
193    const CPDF_OCContext::UsageType usage = (flags & FPDF_PRINTING)
194            ? CPDF_OCContext::Print : CPDF_OCContext::View;
195
196    renderOptions->m_AddFlags = flags >> 8;
197    renderOptions->m_pOCContext = new CPDF_OCContext(pPage->m_pDocument, usage);
198
199    fxgeDevice->SaveState();
200
201    FX_RECT clip;
202    clip.left = destLeft;
203    clip.right = destRight;
204    clip.top = destTop;
205    clip.bottom = destBottom;
206    fxgeDevice->SetClip_Rect(&clip);
207
208    CPDF_RenderContext* pageContext = new CPDF_RenderContext(pPage);
209    pContext->m_pContext = pageContext;
210
211    CFX_Matrix matrix;
212    if (!transform) {
213        pPage->GetDisplayMatrix(matrix, destLeft, destTop, destRight - destLeft,
214                destBottom - destTop, 0);
215    } else {
216        // PDF's coordinate system origin is left-bottom while
217        // in graphics it is the top-left, so remap the origin.
218        matrix.Set(1, 0, 0, -1, 0, pPage->GetPageHeight());
219
220        SkScalar transformValues[6];
221        if (transform->asAffine(transformValues)) {
222            matrix.Concat(transformValues[SkMatrix::kAScaleX], transformValues[SkMatrix::kASkewY],
223                    transformValues[SkMatrix::kASkewX], transformValues[SkMatrix::kAScaleY],
224                    transformValues[SkMatrix::kATransX], transformValues[SkMatrix::kATransY]);
225        } else {
226            // Already checked for a return value of false in the caller, so this should never
227            // happen.
228            ALOGE("Error rendering page!");
229        }
230
231    }
232    pageContext->AppendObjectList(pPage, &matrix);
233
234    pContext->m_pRenderer = new CPDF_ProgressiveRenderer(pageContext, fxgeDevice, renderOptions);
235    pContext->m_pRenderer->Start(NULL);
236
237    fxgeDevice->RestoreState();
238
239    pPage->RemovePrivateData((void*) 1);
240
241    delete pContext;
242}
243
244static void nativeRenderPage(JNIEnv* env, jclass thiz, jlong documentPtr, jlong pagePtr,
245        jobject jbitmap, jint destLeft, jint destTop, jint destRight, jint destBottom,
246        jlong matrixPtr, jint renderMode) {
247
248    FPDF_PAGE page = reinterpret_cast<FPDF_PAGE>(pagePtr);
249    SkMatrix* skMatrix = reinterpret_cast<SkMatrix*>(matrixPtr);
250
251    SkBitmap skBitmap;
252    GraphicsJNI::getSkBitmap(env, jbitmap, &skBitmap);
253
254    SkAutoLockPixels alp(skBitmap);
255
256    const int stride = skBitmap.width() * 4;
257
258    FPDF_BITMAP bitmap = FPDFBitmap_CreateEx(skBitmap.width(), skBitmap.height(),
259            FPDFBitmap_BGRA, skBitmap.getPixels(), stride);
260
261    if (!bitmap) {
262        ALOGE("Erorr creating bitmap");
263        return;
264    }
265
266    int renderFlags = 0;
267    if (renderMode == RENDER_MODE_FOR_DISPLAY) {
268        renderFlags |= FPDF_LCD_TEXT;
269    } else if (renderMode == RENDER_MODE_FOR_PRINT) {
270        renderFlags |= FPDF_PRINTING;
271    }
272
273    if (skMatrix && !skMatrix->asAffine(NULL)) {
274        jniThrowException(env, "java/lang/IllegalArgumentException",
275                "transform matrix has perspective. Only affine matrices are allowed.");
276        return;
277    }
278
279    renderPageBitmap(bitmap, page, destLeft, destTop, destRight,
280            destBottom, skMatrix, renderFlags);
281
282    skBitmap.notifyPixelsChanged();
283}
284
285static const JNINativeMethod gPdfRenderer_Methods[] = {
286    {"nativeCreate", "(IJ)J", (void*) nativeCreate},
287    {"nativeClose", "(J)V", (void*) nativeClose},
288    {"nativeGetPageCount", "(J)I", (void*) nativeGetPageCount},
289    {"nativeScaleForPrinting", "(J)Z", (void*) nativeScaleForPrinting},
290    {"nativeRenderPage", "(JJLandroid/graphics/Bitmap;IIIIJI)V", (void*) nativeRenderPage},
291    {"nativeOpenPageAndGetSize", "(JILandroid/graphics/Point;)J", (void*) nativeOpenPageAndGetSize},
292    {"nativeClosePage", "(J)V", (void*) nativeClosePage}
293};
294
295int register_android_graphics_pdf_PdfRenderer(JNIEnv* env) {
296    int result = RegisterMethodsOrDie(
297            env, "android/graphics/pdf/PdfRenderer", gPdfRenderer_Methods,
298            NELEM(gPdfRenderer_Methods));
299
300    jclass clazz = FindClassOrDie(env, "android/graphics/Point");
301    gPointClassInfo.x = GetFieldIDOrDie(env, clazz, "x", "I");
302    gPointClassInfo.y = GetFieldIDOrDie(env, clazz, "y", "I");
303
304    return result;
305};
306
307};
308