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 
18 package com.android.bips.jni;
19 
20 import android.content.ComponentName;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.content.ServiceConnection;
24 import android.os.IBinder;
25 import android.os.ParcelFileDescriptor;
26 import android.os.RemoteException;
27 import android.util.Log;
28 
29 import com.android.bips.render.IPdfRender;
30 import com.android.bips.render.PdfRenderService;
31 
32 import java.io.File;
33 import java.io.FileNotFoundException;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.nio.ByteBuffer;
37 
38 /**
39  * Renders pages of a PDF into an RGB buffer. For security, relies on a remote rendering service.
40  */
41 public 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 final Object sLock = new Object();
47     private static PdfRender sInstance;
48 
49     private final Context mContext;
50     private final Intent mIntent;
51     private IPdfRender mService;
52     private String mCurrentFile;
53 
54     /**
55      * Returns the PdfRender singleton, creating it if necessary.
56      */
getInstance(Context context)57     public static PdfRender getInstance(Context context) {
58         // Native code might call this without a context
59         synchronized (sLock) {
60             if (sInstance == null && context != null) {
61                 sInstance = new PdfRender(context.getApplicationContext());
62             }
63 
64             return sInstance;
65         }
66     }
67 
68     private ServiceConnection mConnection = new ServiceConnection() {
69         public void onServiceConnected(ComponentName className, IBinder service) {
70             if (DEBUG) Log.d(TAG, "service connected");
71             mService = IPdfRender.Stub.asInterface(service);
72         }
73 
74         public void onServiceDisconnected(ComponentName className) {
75             Log.w(TAG, "PdfRender service unexpectedly disconnected, reconnecting");
76             mService = null;
77             mContext.bindService(mIntent, this, Context.BIND_AUTO_CREATE);
78         }
79     };
80 
PdfRender(Context context)81     private PdfRender(Context context) {
82         mContext = context;
83         mIntent = new Intent(context, PdfRenderService.class);
84         context.bindService(mIntent, mConnection, Context.BIND_AUTO_CREATE);
85     }
86 
87     /** Shut down the PDF renderer */
close()88     public void close() {
89         mContext.unbindService(mConnection);
90         mService = null;
91 
92         synchronized (sLock) {
93             sInstance = null;
94         }
95     }
96 
97     /**
98      * Opens the specified document, returning the page count or 0 on error. (Called by native
99      * code.)
100      */
openDocument(String fileName)101     private int openDocument(String fileName) {
102         if (DEBUG) Log.d(TAG, "openDocument() " + fileName);
103         if (mService == null) {
104             return 0;
105         }
106 
107         if (mCurrentFile != null && !mCurrentFile.equals(fileName)) {
108             closeDocument();
109         }
110 
111         try {
112             ParcelFileDescriptor pfd = ParcelFileDescriptor.open(new File(fileName),
113                     ParcelFileDescriptor.MODE_READ_ONLY);
114             return mService.openDocument(pfd);
115         } catch (RemoteException | FileNotFoundException ex) {
116             Log.w(TAG, "Failed to open " + fileName, ex);
117             return 0;
118         }
119     }
120 
121     /**
122      * Returns the size of the specified page or null on error. (Called by native code.)
123      * @param page 0-based page
124      * @return width and height of page in points (1/72")
125      */
getPageSize(int page)126     public SizeD getPageSize(int page) {
127         if (DEBUG) Log.d(TAG, "getPageSize() page=" + page);
128         if (mService == null) {
129             return null;
130         }
131 
132         try {
133             return mService.getPageSize(page - 1);
134         } catch (RemoteException | IllegalArgumentException ex) {
135             Log.w(TAG, "getPageWidth failed", ex);
136             return null;
137         }
138     }
139 
140     /**
141      * Renders the content of the page. (Called by native code.)
142      * @param page 0-based page
143      * @param y y-offset onto page
144      * @param width width of area to render
145      * @param height height of area to render
146      * @param zoomFactor zoom factor to use when rendering data
147      * @param target target byte buffer to fill with results
148      * @return true if rendering was successful
149      */
renderPageStripe(int page, int y, int width, int height, double zoomFactor, ByteBuffer target)150     public boolean renderPageStripe(int page, int y, int width, int height,
151             double zoomFactor, ByteBuffer target) {
152         if (DEBUG) {
153             Log.d(TAG, "renderPageStripe() page=" + page + " y=" + y + " w=" + width
154                     + " h=" + height + " zoom=" + zoomFactor);
155         }
156         if (mService == null) {
157             return false;
158         }
159 
160         try {
161             long start = System.currentTimeMillis();
162             ParcelFileDescriptor input = mService.renderPageStripe(page - 1, y, width, height,
163                     zoomFactor);
164 
165             // Copy received data into the ByteBuffer
166             int expectedSize = width * height * 3;
167             byte[] readBuffer = new byte[128 * 1024];
168             try (InputStream in = new ParcelFileDescriptor.AutoCloseInputStream(input)) {
169                 int length;
170                 while ((length = in.read(readBuffer, 0, readBuffer.length)) > 0) {
171                     target.put(readBuffer, 0, length);
172                 }
173             }
174             if (target.position() != expectedSize) {
175                 Log.w(TAG, "Render failed: expected " + target.position() + ", got "
176                         + expectedSize + " bytes");
177                 return false;
178             }
179 
180             if (DEBUG) Log.d(TAG, "Received (" + (System.currentTimeMillis() - start) + "ms)");
181             return true;
182         } catch (RemoteException | IOException | IllegalArgumentException | OutOfMemoryError ex) {
183             Log.w(TAG, "Render failed", ex);
184             return false;
185         }
186     }
187 
188     /**
189      * Releases any open resources for the current document and page.
190      */
closeDocument()191     public void closeDocument() {
192         if (DEBUG) Log.d(TAG, "closeDocument()");
193         if (mService == null) {
194             return;
195         }
196 
197         try {
198             mService.closeDocument();
199         } catch (RemoteException ignored) {
200         }
201     }
202 }
203