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