Util.java revision 16ca94d73bfe07f280e381595709b56c2681b2bc
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    public static float[] convertZoomRatios(List<Integer> zoomRatios) {
384        float result[] = new float[zoomRatios.size()];
385        for (int i = 0, n = result.length; i < n; ++i) {
386            result[i] = (float) zoomRatios.get(i) / 100f;
387        }
388        return result;
389    }
390
391    /**
392     * Returns whether the device is voice-capable (meaning, it can do MMS).
393     */
394    public static boolean isMmsCapable(Context context) {
395        TelephonyManager telephonyManager = (TelephonyManager)
396                context.getSystemService(Context.TELEPHONY_SERVICE);
397        if (telephonyManager == null) {
398            return false;
399        }
400
401        try {
402            Class partypes[] = new Class[0];
403            Method sIsVoiceCapable = TelephonyManager.class.getMethod(
404                    "isVoiceCapable", partypes);
405
406            Object arglist[] = new Object[0];
407            Object retobj = sIsVoiceCapable.invoke(telephonyManager, arglist);
408            return (Boolean) retobj;
409        } catch (java.lang.reflect.InvocationTargetException ite) {
410            // Failure, must be another device.
411            // Assume that it is voice capable.
412        } catch (IllegalAccessException iae) {
413            // Failure, must be an other device.
414            // Assume that it is voice capable.
415        } catch (NoSuchMethodException nsme) {
416        }
417        return true;
418    }
419
420    // This is for test only. Allow the camera to launch the specific camera.
421    public static int getCameraFacingIntentExtras(Activity currentActivity) {
422        int cameraId = -1;
423
424        int intentCameraId =
425                currentActivity.getIntent().getIntExtra(Util.EXTRAS_CAMERA_FACING, -1);
426
427        if (isFrontCameraIntent(intentCameraId)) {
428            // Check if the front camera exist
429            int frontCameraId = CameraHolder.instance().getFrontCameraId();
430            if (frontCameraId != -1) {
431                cameraId = frontCameraId;
432            }
433        } else if (isBackCameraIntent(intentCameraId)) {
434            // Check if the back camera exist
435            int backCameraId = CameraHolder.instance().getBackCameraId();
436            if (backCameraId != -1) {
437                cameraId = backCameraId;
438            }
439        }
440        return cameraId;
441    }
442
443    private static boolean isFrontCameraIntent(int intentCameraId) {
444        return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
445    }
446
447    private static boolean isBackCameraIntent(int intentCameraId) {
448        return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK);
449    }
450
451    private static int mLocation[] = new int[2];
452
453    // This method is not thread-safe.
454    public static boolean pointInView(float x, float y, View v) {
455        v.getLocationInWindow(mLocation);
456        return x >= mLocation[0] && x < (mLocation[0] + v.getWidth())
457                && y >= mLocation[1] && y < (mLocation[1] + v.getHeight());
458    }
459
460    public static boolean isUriValid(Uri uri, ContentResolver resolver) {
461        if (uri == null) return false;
462
463        try {
464            ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
465            if (pfd == null) {
466                Log.e(TAG, "Fail to open URI. URI=" + uri);
467                return false;
468            }
469            pfd.close();
470        } catch (IOException ex) {
471            return false;
472        }
473        return true;
474    }
475
476    public static void viewUri(Uri uri, Context context) {
477        if (!isUriValid(uri, context.getContentResolver())) {
478            Log.e(TAG, "Uri invalid. uri=" + uri);
479            return;
480        }
481
482        try {
483            context.startActivity(new Intent(Util.REVIEW_ACTION, uri));
484        } catch (ActivityNotFoundException ex) {
485            try {
486                context.startActivity(new Intent(Intent.ACTION_VIEW, uri));
487            } catch (ActivityNotFoundException e) {
488                Log.e(TAG, "review image fail. uri=" + uri, e);
489            }
490        }
491    }
492}
493