Util.java revision dfb6f208e3f5dd7d68bcaade644aa1d1f1f0a98f
1/*
2 * Copyright (C) 2009 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
17package com.android.camera;
18
19import android.app.Activity;
20import android.app.AlertDialog;
21import android.app.admin.DevicePolicyManager;
22import android.content.ActivityNotFoundException;
23import android.content.ContentResolver;
24import android.content.Context;
25import android.content.DialogInterface;
26import android.content.Intent;
27import android.graphics.Bitmap;
28import android.graphics.BitmapFactory;
29import android.graphics.Matrix;
30import android.hardware.Camera;
31import android.hardware.Camera.Parameters;
32import android.hardware.Camera.Size;
33import android.net.Uri;
34import android.os.Build;
35import android.os.ParcelFileDescriptor;
36import android.telephony.TelephonyManager;
37import android.util.Log;
38import android.view.Display;
39import android.view.Surface;
40import android.view.View;
41
42import java.io.Closeable;
43import java.io.IOException;
44import java.lang.reflect.Method;
45import java.util.List;
46import java.util.StringTokenizer;
47
48/**
49 * Collection of utility functions used in this package.
50 */
51public class Util {
52    private static final String TAG = "Util";
53    private static final int DIRECTION_LEFT = 0;
54    private static final int DIRECTION_RIGHT = 1;
55    private static final int DIRECTION_UP = 2;
56    private static final int DIRECTION_DOWN = 3;
57
58    public static final String REVIEW_ACTION = "com.android.camera.action.REVIEW";
59
60    // Private intent extras. Test only.
61    private static final String EXTRAS_CAMERA_FACING =
62            "android.intent.extras.CAMERA_FACING";
63
64    private Util() {
65    }
66
67    // Rotates the bitmap by the specified degree.
68    // If a new bitmap is created, the original bitmap is recycled.
69    public static Bitmap rotate(Bitmap b, int degrees) {
70        return rotateAndMirror(b, degrees, false);
71    }
72
73    // Rotates and/or mirrors the bitmap. If a new bitmap is created, the
74    // original bitmap is recycled.
75    public static Bitmap rotateAndMirror(Bitmap b, int degrees, boolean mirror) {
76        if ((degrees != 0 || mirror) && b != null) {
77            Matrix m = new Matrix();
78            m.setRotate(degrees,
79                    (float) b.getWidth() / 2, (float) b.getHeight() / 2);
80            if (mirror) {
81                m.postScale(-1, 1);
82                degrees = (degrees + 360) % 360;
83                if (degrees == 0 || degrees == 180) {
84                    m.postTranslate((float) b.getWidth(), 0);
85                } else if (degrees == 90 || degrees == 270) {
86                    m.postTranslate((float) b.getHeight(), 0);
87                } else {
88                    throw new IllegalArgumentException("Invalid degrees=" + degrees);
89                }
90            }
91
92            try {
93                Bitmap b2 = Bitmap.createBitmap(
94                        b, 0, 0, b.getWidth(), b.getHeight(), m, true);
95                if (b != b2) {
96                    b.recycle();
97                    b = b2;
98                }
99            } catch (OutOfMemoryError ex) {
100                // We have no memory to rotate. Return the original bitmap.
101            }
102        }
103        return b;
104    }
105
106    /*
107     * Compute the sample size as a function of minSideLength
108     * and maxNumOfPixels.
109     * minSideLength is used to specify that minimal width or height of a
110     * bitmap.
111     * maxNumOfPixels is used to specify the maximal size in pixels that is
112     * tolerable in terms of memory usage.
113     *
114     * The function returns a sample size based on the constraints.
115     * Both size and minSideLength can be passed in as -1
116     * which indicates no care of the corresponding constraint.
117     * The functions prefers returning a sample size that
118     * generates a smaller bitmap, unless minSideLength = -1.
119     *
120     * Also, the function rounds up the sample size to a power of 2 or multiple
121     * of 8 because BitmapFactory only honors sample size this way.
122     * For example, BitmapFactory downsamples an image by 2 even though the
123     * request is 3. So we round up the sample size to avoid OOM.
124     */
125    public static int computeSampleSize(BitmapFactory.Options options,
126            int minSideLength, int maxNumOfPixels) {
127        int initialSize = computeInitialSampleSize(options, minSideLength,
128                maxNumOfPixels);
129
130        int roundedSize;
131        if (initialSize <= 8) {
132            roundedSize = 1;
133            while (roundedSize < initialSize) {
134                roundedSize <<= 1;
135            }
136        } else {
137            roundedSize = (initialSize + 7) / 8 * 8;
138        }
139
140        return roundedSize;
141    }
142
143    private static int computeInitialSampleSize(BitmapFactory.Options options,
144            int minSideLength, int maxNumOfPixels) {
145        double w = options.outWidth;
146        double h = options.outHeight;
147
148        int lowerBound = (maxNumOfPixels < 0) ? 1 :
149                (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
150        int upperBound = (minSideLength < 0) ? 128 :
151                (int) Math.min(Math.floor(w / minSideLength),
152                Math.floor(h / minSideLength));
153
154        if (upperBound < lowerBound) {
155            // return the larger one when there is no overlapping zone.
156            return lowerBound;
157        }
158
159        if (maxNumOfPixels < 0 && minSideLength < 0) {
160            return 1;
161        } else if (minSideLength < 0) {
162            return lowerBound;
163        } else {
164            return upperBound;
165        }
166    }
167
168    public static Bitmap makeBitmap(byte[] jpegData, int maxNumOfPixels) {
169        try {
170            BitmapFactory.Options options = new BitmapFactory.Options();
171            options.inJustDecodeBounds = true;
172            BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,
173                    options);
174            if (options.mCancel || options.outWidth == -1
175                    || options.outHeight == -1) {
176                return null;
177            }
178            options.inSampleSize = computeSampleSize(
179                    options, -1, maxNumOfPixels);
180            options.inJustDecodeBounds = false;
181
182            options.inDither = false;
183            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
184            return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,
185                    options);
186        } catch (OutOfMemoryError ex) {
187            Log.e(TAG, "Got oom exception ", ex);
188            return null;
189        }
190    }
191
192    public static void closeSilently(Closeable c) {
193        if (c == null) return;
194        try {
195            c.close();
196        } catch (Throwable t) {
197            // do nothing
198        }
199    }
200
201    public static void Assert(boolean cond) {
202        if (!cond) {
203            throw new AssertionError();
204        }
205    }
206
207    public static android.hardware.Camera openCamera(Activity activity, int cameraId)
208            throws CameraHardwareException, CameraDisabledException {
209        // Check if device policy has disabled the camera.
210        DevicePolicyManager dpm = (DevicePolicyManager) activity.getSystemService(
211                Context.DEVICE_POLICY_SERVICE);
212        if (dpm.getCameraDisabled(null)) {
213            throw new CameraDisabledException();
214        }
215
216        try {
217            return CameraHolder.instance().open(cameraId);
218        } catch (CameraHardwareException e) {
219            // In eng build, we throw the exception so that test tool
220            // can detect it and report it
221            if ("eng".equals(Build.TYPE)) {
222                throw new RuntimeException("openCamera failed", e);
223            } else {
224                throw e;
225            }
226        }
227    }
228
229    public static void showErrorAndFinish(final Activity activity, int msgId) {
230        DialogInterface.OnClickListener buttonListener =
231                new DialogInterface.OnClickListener() {
232            public void onClick(DialogInterface dialog, int which) {
233                activity.finish();
234            }
235        };
236        new AlertDialog.Builder(activity)
237                .setCancelable(false)
238                .setIconAttribute(android.R.attr.alertDialogIcon)
239                .setTitle(R.string.camera_error_title)
240                .setMessage(msgId)
241                .setNeutralButton(R.string.details_ok, buttonListener)
242                .show();
243    }
244
245    public static <T> T checkNotNull(T object) {
246        if (object == null) throw new NullPointerException();
247        return object;
248    }
249
250    public static boolean equals(Object a, Object b) {
251        return (a == b) || (a == null ? false : a.equals(b));
252    }
253
254    public static int nextPowerOf2(int n) {
255        n -= 1;
256        n |= n >>> 16;
257        n |= n >>> 8;
258        n |= n >>> 4;
259        n |= n >>> 2;
260        n |= n >>> 1;
261        return n + 1;
262    }
263
264    public static float distance(float x, float y, float sx, float sy) {
265        float dx = x - sx;
266        float dy = y - sy;
267        return (float) Math.sqrt(dx * dx + dy * dy);
268    }
269
270    public static int clamp(int x, int min, int max) {
271        if (x > max) return max;
272        if (x < min) return min;
273        return x;
274    }
275
276    public static int getDisplayRotation(Activity activity) {
277        int rotation = activity.getWindowManager().getDefaultDisplay()
278                .getRotation();
279        switch (rotation) {
280            case Surface.ROTATION_0: return 0;
281            case Surface.ROTATION_90: return 90;
282            case Surface.ROTATION_180: return 180;
283            case Surface.ROTATION_270: return 270;
284        }
285        return 0;
286    }
287
288    public static void setCameraDisplayOrientation(int degrees,
289            int cameraId, Camera camera) {
290        // See android.hardware.Camera.setCameraDisplayOrientation for
291        // documentation.
292        Camera.CameraInfo info = new Camera.CameraInfo();
293        Camera.getCameraInfo(cameraId, info);
294        int result;
295        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
296            result = (info.orientation + degrees) % 360;
297            result = (360 - result) % 360;  // compensate the mirror
298        } else {  // back-facing
299            result = (info.orientation - degrees + 360) % 360;
300        }
301        camera.setDisplayOrientation(result);
302    }
303
304    public static Size getOptimalPreviewSize(Activity currentActivity,
305            List<Size> sizes, double targetRatio) {
306        // Use a very small tolerance because we want an exact match.
307        final double ASPECT_TOLERANCE = 0.001;
308        if (sizes == null) return null;
309
310        Size optimalSize = null;
311        double minDiff = Double.MAX_VALUE;
312
313        // Because of bugs of overlay and layout, we sometimes will try to
314        // layout the viewfinder in the portrait orientation and thus get the
315        // wrong size of mSurfaceView. When we change the preview size, the
316        // new overlay will be created before the old one closed, which causes
317        // an exception. For now, just get the screen size
318
319        Display display = currentActivity.getWindowManager().getDefaultDisplay();
320        int targetHeight = Math.min(display.getHeight(), display.getWidth());
321
322        if (targetHeight <= 0) {
323            // We don't know the size of SurfaceView, use screen height
324            targetHeight = display.getHeight();
325        }
326
327        // Try to find an size match aspect ratio and size
328        for (Size size : sizes) {
329            double ratio = (double) size.width / size.height;
330            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
331            if (Math.abs(size.height - targetHeight) < minDiff) {
332                optimalSize = size;
333                minDiff = Math.abs(size.height - targetHeight);
334            }
335        }
336
337        // Cannot find the one match the aspect ratio. This should not happen.
338        // Ignore the requirement.
339        if (optimalSize == null) {
340            Log.w(TAG, "No preview size match the aspect ratio");
341            minDiff = Double.MAX_VALUE;
342            for (Size size : sizes) {
343                if (Math.abs(size.height - targetHeight) < minDiff) {
344                    optimalSize = size;
345                    minDiff = Math.abs(size.height - targetHeight);
346                }
347            }
348        }
349        return optimalSize;
350    }
351
352    public static void dumpParameters(Parameters parameters) {
353        String flattened = parameters.flatten();
354        StringTokenizer tokenizer = new StringTokenizer(flattened, ";");
355        Log.d(TAG, "Dump all camera parameters:");
356        while (tokenizer.hasMoreElements()) {
357            Log.d(TAG, tokenizer.nextToken());
358        }
359    }
360
361    /**
362     * Returns whether the device is voice-capable (meaning, it can do MMS).
363     */
364    public static boolean isMmsCapable(Context context) {
365        TelephonyManager telephonyManager = (TelephonyManager)
366                context.getSystemService(Context.TELEPHONY_SERVICE);
367        if (telephonyManager == null) {
368            return false;
369        }
370
371        try {
372            Class partypes[] = new Class[0];
373            Method sIsVoiceCapable = TelephonyManager.class.getMethod(
374                    "isVoiceCapable", partypes);
375
376            Object arglist[] = new Object[0];
377            Object retobj = sIsVoiceCapable.invoke(telephonyManager, arglist);
378            return (Boolean) retobj;
379        } catch (java.lang.reflect.InvocationTargetException ite) {
380            // Failure, must be another device.
381            // Assume that it is voice capable.
382        } catch (IllegalAccessException iae) {
383            // Failure, must be an other device.
384            // Assume that it is voice capable.
385        } catch (NoSuchMethodException nsme) {
386        }
387        return true;
388    }
389
390    // This is for test only. Allow the camera to launch the specific camera.
391    public static int getCameraFacingIntentExtras(Activity currentActivity) {
392        int cameraId = -1;
393
394        int intentCameraId =
395                currentActivity.getIntent().getIntExtra(Util.EXTRAS_CAMERA_FACING, -1);
396
397        if (isFrontCameraIntent(intentCameraId)) {
398            // Check if the front camera exist
399            int frontCameraId = CameraHolder.instance().getFrontCameraId();
400            if (frontCameraId != -1) {
401                cameraId = frontCameraId;
402            }
403        } else if (isBackCameraIntent(intentCameraId)) {
404            // Check if the back camera exist
405            int backCameraId = CameraHolder.instance().getBackCameraId();
406            if (backCameraId != -1) {
407                cameraId = backCameraId;
408            }
409        }
410        return cameraId;
411    }
412
413    private static boolean isFrontCameraIntent(int intentCameraId) {
414        return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
415    }
416
417    private static boolean isBackCameraIntent(int intentCameraId) {
418        return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK);
419    }
420
421    private static int mLocation[] = new int[2];
422
423    // This method is not thread-safe.
424    public static boolean pointInView(float x, float y, View v) {
425        v.getLocationInWindow(mLocation);
426        return x >= mLocation[0] && x < (mLocation[0] + v.getWidth())
427                && y >= mLocation[1] && y < (mLocation[1] + v.getHeight());
428    }
429
430    public static boolean isUriValid(Uri uri, ContentResolver resolver) {
431        if (uri == null) return false;
432
433        try {
434            ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
435            if (pfd == null) {
436                Log.e(TAG, "Fail to open URI. URI=" + uri);
437                return false;
438            }
439            pfd.close();
440        } catch (IOException ex) {
441            return false;
442        }
443        return true;
444    }
445
446    public static void viewUri(Uri uri, Context context) {
447        if (!isUriValid(uri, context.getContentResolver())) {
448            Log.e(TAG, "Uri invalid. uri=" + uri);
449            return;
450        }
451
452        try {
453            context.startActivity(new Intent(Util.REVIEW_ACTION, uri));
454        } catch (ActivityNotFoundException ex) {
455            try {
456                context.startActivity(new Intent(Intent.ACTION_VIEW, uri));
457            } catch (ActivityNotFoundException e) {
458                Log.e(TAG, "review image fail. uri=" + uri, e);
459            }
460        }
461    }
462}
463