1/*
2 * Copyright (C) 2016 The Android Open Source Project
3 * Copyright (C) 2015-2016 Mopria Alliance, Inc.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.bips.jni;
19
20import android.content.ComponentName;
21import android.content.Context;
22import android.content.Intent;
23import android.content.ServiceConnection;
24import android.os.IBinder;
25import android.os.ParcelFileDescriptor;
26import android.os.RemoteException;
27import android.util.Log;
28
29import com.android.bips.render.IPdfRender;
30import com.android.bips.render.PdfRenderService;
31
32import java.io.File;
33import java.io.FileNotFoundException;
34import java.io.IOException;
35import java.io.InputStream;
36import java.nio.ByteBuffer;
37
38/**
39 * Renders pages of a PDF into an RGB buffer. For security, relies on a remote rendering service.
40 */
41public class PdfRender {
42    private static final String TAG = PdfRender.class.getSimpleName();
43    private static final boolean DEBUG = false;
44
45    /** The current singleton instance */
46    private static PdfRender sInstance;
47
48    private final Context mContext;
49    private final Intent mIntent;
50    private IPdfRender mService;
51    private String mCurrentFile;
52
53    /**
54     * Returns the PdfRender singleton, creating it if necessary.
55     */
56    public static PdfRender getInstance(Context context) {
57        // Native code might call this without a context
58        if (sInstance == null && context != null) {
59            synchronized(PdfRender.class) {
60                sInstance = new PdfRender(context.getApplicationContext());
61            }
62        }
63        return sInstance;
64    }
65
66    private ServiceConnection mConnection = new ServiceConnection() {
67        public void onServiceConnected(ComponentName className, IBinder service) {
68            if (DEBUG) Log.d(TAG, "service connected");
69            mService = IPdfRender.Stub.asInterface(service);
70        }
71
72        public void onServiceDisconnected(ComponentName className) {
73            Log.w(TAG, "PdfRender service unexpectedly disconnected, reconnecting");
74            mService = null;
75            mContext.bindService(mIntent, this, Context.BIND_AUTO_CREATE);
76        }
77    };
78
79    private PdfRender(Context context) {
80        mContext = context;
81        mIntent = new Intent(context, PdfRenderService.class);
82        context.bindService(mIntent, mConnection, Context.BIND_AUTO_CREATE);
83    }
84
85    /** Shut down the PDF renderer */
86    public void close() {
87        mContext.unbindService(mConnection);
88        mService = null;
89        sInstance = null;
90    }
91
92    /**
93     * Opens the specified document, returning the page count or 0 on error. (Called by native
94     * code.)
95     */
96    private int openDocument(String fileName) {
97        if (DEBUG) Log.d(TAG, "openDocument() " + fileName);
98        if (mService == null) return 0;
99
100        if (mCurrentFile != null && !mCurrentFile.equals(fileName)) {
101            closeDocument();
102        }
103
104        try {
105            ParcelFileDescriptor pfd = ParcelFileDescriptor.open(new File(fileName),
106                    ParcelFileDescriptor.MODE_READ_ONLY);
107            return mService.openDocument(pfd);
108        } catch (RemoteException | FileNotFoundException ex) {
109            Log.w(TAG, "Failed to open " + fileName, ex);
110            return 0;
111        }
112    }
113
114    /**
115     * Returns the size of the specified page or null on error. (Called by native code.)
116     * @param page 0-based page
117     * @return width and height of page in points (1/72")
118     */
119    public SizeD getPageSize(int page) {
120        if (DEBUG) Log.d(TAG, "getPageSize() page=" + page);
121        if (mService == null) return null;
122
123        try {
124            return mService.getPageSize(page - 1);
125        } catch (RemoteException | IllegalArgumentException ex) {
126            Log.w(TAG, "getPageWidth failed", ex);
127            return null;
128        }
129    }
130
131    /**
132     * Renders the content of the page. (Called by native code.)
133     * @param page 0-based page
134     * @param y y-offset onto page
135     * @param width width of area to render
136     * @param height height of area to render
137     * @param zoomFactor zoom factor to use when rendering data
138     * @param target target byte buffer to fill with results
139     * @return true if rendering was successful
140     */
141    public boolean renderPageStripe(int page, int y, int width, int height,
142            double zoomFactor, ByteBuffer target) {
143        if (DEBUG) {
144            Log.d(TAG, "renderPageStripe() page=" + page + " y=" + y + " w=" + width +
145                    " h=" + height + " zoom=" + zoomFactor);
146        }
147        if (mService == null) return false;
148
149        try {
150            long start = System.currentTimeMillis();
151            ParcelFileDescriptor input = mService.renderPageStripe(page - 1, y, width, height,
152                    zoomFactor);
153
154            // Copy received data into the ByteBuffer
155            int expectedSize = width * height * 3;
156            byte[] readBuffer = new byte[128 * 1024];
157            try (InputStream in = new ParcelFileDescriptor.AutoCloseInputStream(input)) {
158                int length;
159                while((length = in.read(readBuffer, 0, readBuffer.length)) > 0) {
160                    target.put(readBuffer, 0, length);
161                }
162            }
163            if (target.position() != expectedSize) {
164                Log.w(TAG, "Render failed: expected " + target.position() + ", got " +
165                        expectedSize + " bytes");
166                return false;
167            }
168
169            if (DEBUG) Log.d(TAG, "Received (" + (System.currentTimeMillis() - start) + "ms)");
170            return true;
171        } catch (RemoteException | IOException | IllegalArgumentException | OutOfMemoryError ex) {
172            Log.w(TAG, "Render failed", ex);
173            return false;
174        }
175    }
176
177    /**
178     * Releases any open resources for the current document and page.
179     */
180    public void closeDocument() {
181        if (DEBUG) Log.d(TAG, "closeDocument()");
182        if (mService == null) return;
183
184        try {
185            mService.closeDocument();
186        } catch (RemoteException ignored) {
187        }
188    }
189}