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