Util.java revision 5be37a20b9086be505ebd424a4b92967800038c8
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            m.setRotate(degrees,
119                    (float) b.getWidth() / 2, (float) b.getHeight() / 2);
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
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 android.hardware.Camera 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            public void onClick(DialogInterface dialog, int which) {
273                activity.finish();
274            }
275        };
276        new AlertDialog.Builder(activity)
277                .setCancelable(false)
278                .setIconAttribute(android.R.attr.alertDialogIcon)
279                .setTitle(R.string.camera_error_title)
280                .setMessage(msgId)
281                .setNeutralButton(R.string.dialog_ok, buttonListener)
282                .show();
283    }
284
285    public static <T> T checkNotNull(T object) {
286        if (object == null) throw new NullPointerException();
287        return object;
288    }
289
290    public static boolean equals(Object a, Object b) {
291        return (a == b) || (a == null ? false : a.equals(b));
292    }
293
294    public static int nextPowerOf2(int n) {
295        n -= 1;
296        n |= n >>> 16;
297        n |= n >>> 8;
298        n |= n >>> 4;
299        n |= n >>> 2;
300        n |= n >>> 1;
301        return n + 1;
302    }
303
304    public static float distance(float x, float y, float sx, float sy) {
305        float dx = x - sx;
306        float dy = y - sy;
307        return (float) Math.sqrt(dx * dx + dy * dy);
308    }
309
310    public static int clamp(int x, int min, int max) {
311        if (x > max) return max;
312        if (x < min) return min;
313        return x;
314    }
315
316    public static int getDisplayRotation(Activity activity) {
317        int rotation = activity.getWindowManager().getDefaultDisplay()
318                .getRotation();
319        switch (rotation) {
320            case Surface.ROTATION_0: return 0;
321            case Surface.ROTATION_90: return 90;
322            case Surface.ROTATION_180: return 180;
323            case Surface.ROTATION_270: return 270;
324        }
325        return 0;
326    }
327
328    public static int getDisplayOrientation(int degrees, int cameraId) {
329        // See android.hardware.Camera.setDisplayOrientation for
330        // documentation.
331        Camera.CameraInfo info = new Camera.CameraInfo();
332        Camera.getCameraInfo(cameraId, info);
333        int result;
334        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
335            result = (info.orientation + degrees) % 360;
336            result = (360 - result) % 360;  // compensate the mirror
337        } else {  // back-facing
338            result = (info.orientation - degrees + 360) % 360;
339        }
340        return result;
341    }
342
343    public static Size getOptimalPreviewSize(Activity currentActivity,
344            List<Size> sizes, double targetRatio) {
345        // Use a very small tolerance because we want an exact match.
346        final double ASPECT_TOLERANCE = 0.001;
347        if (sizes == null) return null;
348
349        Size optimalSize = null;
350        double minDiff = Double.MAX_VALUE;
351
352        // Because of bugs of overlay and layout, we sometimes will try to
353        // layout the viewfinder in the portrait orientation and thus get the
354        // wrong size of mSurfaceView. When we change the preview size, the
355        // new overlay will be created before the old one closed, which causes
356        // an exception. For now, just get the screen size
357
358        Display display = currentActivity.getWindowManager().getDefaultDisplay();
359        int targetHeight = Math.min(display.getHeight(), display.getWidth());
360
361        if (targetHeight <= 0) {
362            // We don't know the size of SurfaceView, use screen height
363            targetHeight = display.getHeight();
364        }
365
366        // Try to find an size match aspect ratio and size
367        for (Size size : sizes) {
368            double ratio = (double) size.width / size.height;
369            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
370            if (Math.abs(size.height - targetHeight) < minDiff) {
371                optimalSize = size;
372                minDiff = Math.abs(size.height - targetHeight);
373            }
374        }
375
376        // Cannot find the one match the aspect ratio. This should not happen.
377        // Ignore the requirement.
378        if (optimalSize == null) {
379            Log.w(TAG, "No preview size match the aspect ratio");
380            minDiff = Double.MAX_VALUE;
381            for (Size size : sizes) {
382                if (Math.abs(size.height - targetHeight) < minDiff) {
383                    optimalSize = size;
384                    minDiff = Math.abs(size.height - targetHeight);
385                }
386            }
387        }
388        return optimalSize;
389    }
390
391    public static void dumpParameters(Parameters parameters) {
392        String flattened = parameters.flatten();
393        StringTokenizer tokenizer = new StringTokenizer(flattened, ";");
394        Log.d(TAG, "Dump all camera parameters:");
395        while (tokenizer.hasMoreElements()) {
396            Log.d(TAG, tokenizer.nextToken());
397        }
398    }
399
400    /**
401     * Returns whether the device is voice-capable (meaning, it can do MMS).
402     */
403    public static boolean isMmsCapable(Context context) {
404        TelephonyManager telephonyManager = (TelephonyManager)
405                context.getSystemService(Context.TELEPHONY_SERVICE);
406        if (telephonyManager == null) {
407            return false;
408        }
409
410        try {
411            Class partypes[] = new Class[0];
412            Method sIsVoiceCapable = TelephonyManager.class.getMethod(
413                    "isVoiceCapable", partypes);
414
415            Object arglist[] = new Object[0];
416            Object retobj = sIsVoiceCapable.invoke(telephonyManager, arglist);
417            return (Boolean) retobj;
418        } catch (java.lang.reflect.InvocationTargetException ite) {
419            // Failure, must be another device.
420            // Assume that it is voice capable.
421        } catch (IllegalAccessException iae) {
422            // Failure, must be an other device.
423            // Assume that it is voice capable.
424        } catch (NoSuchMethodException nsme) {
425        }
426        return true;
427    }
428
429    // This is for test only. Allow the camera to launch the specific camera.
430    public static int getCameraFacingIntentExtras(Activity currentActivity) {
431        int cameraId = -1;
432
433        int intentCameraId =
434                currentActivity.getIntent().getIntExtra(Util.EXTRAS_CAMERA_FACING, -1);
435
436        if (isFrontCameraIntent(intentCameraId)) {
437            // Check if the front camera exist
438            int frontCameraId = CameraHolder.instance().getFrontCameraId();
439            if (frontCameraId != -1) {
440                cameraId = frontCameraId;
441            }
442        } else if (isBackCameraIntent(intentCameraId)) {
443            // Check if the back camera exist
444            int backCameraId = CameraHolder.instance().getBackCameraId();
445            if (backCameraId != -1) {
446                cameraId = backCameraId;
447            }
448        }
449        return cameraId;
450    }
451
452    private static boolean isFrontCameraIntent(int intentCameraId) {
453        return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
454    }
455
456    private static boolean isBackCameraIntent(int intentCameraId) {
457        return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK);
458    }
459
460    private static int mLocation[] = new int[2];
461
462    // This method is not thread-safe.
463    public static boolean pointInView(float x, float y, View v) {
464        v.getLocationInWindow(mLocation);
465        return x >= mLocation[0] && x < (mLocation[0] + v.getWidth())
466                && y >= mLocation[1] && y < (mLocation[1] + v.getHeight());
467    }
468
469    public static boolean isUriValid(Uri uri, ContentResolver resolver) {
470        if (uri == null) return false;
471
472        try {
473            ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
474            if (pfd == null) {
475                Log.e(TAG, "Fail to open URI. URI=" + uri);
476                return false;
477            }
478            pfd.close();
479        } catch (IOException ex) {
480            return false;
481        }
482        return true;
483    }
484
485    public static void viewUri(Uri uri, Context context) {
486        if (!isUriValid(uri, context.getContentResolver())) {
487            Log.e(TAG, "Uri invalid. uri=" + uri);
488            return;
489        }
490
491        try {
492            context.startActivity(new Intent(Util.REVIEW_ACTION, uri));
493        } catch (ActivityNotFoundException ex) {
494            try {
495                context.startActivity(new Intent(Intent.ACTION_VIEW, uri));
496            } catch (ActivityNotFoundException e) {
497                Log.e(TAG, "review image fail. uri=" + uri, e);
498            }
499        }
500    }
501
502    public static void prepareMatrix(Matrix matrix, boolean mirror, int displayOrientation,
503            int viewWidth, int viewHeight) {
504        // Need mirror for front camera.
505        matrix.setScale(mirror ? -1 : 1, 1);
506        // This is the value for android.hardware.Camera.setDisplayOrientation.
507        matrix.postRotate(displayOrientation);
508        // Camera driver coordinates range from (-1000, -1000) to (1000, 1000).
509        // UI coordinates range from (0, 0) to (width, height).
510        matrix.postScale(viewWidth / 2000f, viewHeight / 2000f);
511        matrix.postTranslate(viewWidth / 2f, viewHeight / 2f);
512    }
513
514    public static String createJpegName(long dateTaken) {
515        Date date = new Date(dateTaken);
516        SimpleDateFormat dateFormat = new SimpleDateFormat(sImageFileNameFormat);
517        return dateFormat.format(date);
518    }
519
520    public static void broadcastNewPicture(Context context, Uri uri) {
521        context.sendBroadcast(new Intent(android.hardware.Camera.ACTION_NEW_PICTURE, uri));
522        // Keep compatibility
523        context.sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", uri));
524    }
525
526    public static void fadeIn(View view) {
527        if (view.getVisibility() == View.VISIBLE) return;
528
529        view.setVisibility(View.VISIBLE);
530        Animation animation = new AlphaAnimation(0F, 1F);
531        animation.setDuration(400);
532        view.startAnimation(animation);
533    }
534
535    public static void fadeOut(View view) {
536        if (view.getVisibility() != View.VISIBLE) return;
537
538        Animation animation = new AlphaAnimation(1F, 0F);
539        animation.setDuration(400);
540        view.startAnimation(animation);
541        view.setVisibility(View.GONE);
542    }
543
544    public static void setRotationParameter(Parameters parameters, int cameraId, int orientation) {
545        // See android.hardware.Camera.Parameters.setRotation for
546        // documentation.
547        int rotation = 0;
548        if (orientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
549            CameraInfo info = CameraHolder.instance().getCameraInfo()[cameraId];
550            if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
551                rotation = (info.orientation - orientation + 360) % 360;
552            } else {  // back-facing camera
553                rotation = (info.orientation + orientation) % 360;
554            }
555        }
556        parameters.setRotation(rotation);
557    }
558
559    public static void setGpsParameters(Parameters parameters, Location loc) {
560        // Clear previous GPS location from the parameters.
561        parameters.removeGpsData();
562
563        // We always encode GpsTimeStamp
564        parameters.setGpsTimestamp(System.currentTimeMillis() / 1000);
565
566        // Set GPS location.
567        if (loc != null) {
568            double lat = loc.getLatitude();
569            double lon = loc.getLongitude();
570            boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
571
572            if (hasLatLon) {
573                Log.d(TAG, "Set gps location");
574                parameters.setGpsLatitude(lat);
575                parameters.setGpsLongitude(lon);
576                parameters.setGpsProcessingMethod(loc.getProvider().toUpperCase());
577                if (loc.hasAltitude()) {
578                    parameters.setGpsAltitude(loc.getAltitude());
579                } else {
580                    // for NETWORK_PROVIDER location provider, we may have
581                    // no altitude information, but the driver needs it, so
582                    // we fake one.
583                    parameters.setGpsAltitude(0);
584                }
585                if (loc.getTime() != 0) {
586                    // Location.getTime() is UTC in milliseconds.
587                    // gps-timestamp is UTC in seconds.
588                    long utcTimeSeconds = loc.getTime() / 1000;
589                    parameters.setGpsTimestamp(utcTimeSeconds);
590                }
591            } else {
592                loc = null;
593            }
594        }
595    }
596
597    public static void enterLightsOutMode(Window window) {
598        WindowManager.LayoutParams params = window.getAttributes();
599        params.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE;
600        window.setAttributes(params);
601    }
602
603    public static void initializeScreenBrightness(Window win, ContentResolver resolver) {
604        // Overright the brightness settings if it is automatic
605        int mode = Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
606                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
607        if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
608            WindowManager.LayoutParams winParams = win.getAttributes();
609            winParams.screenBrightness = DEFAULT_CAMERA_BRIGHTNESS;
610            win.setAttributes(winParams);
611        }
612    }
613}
614