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