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