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