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