Util.java revision 8ab2b624d51b3b8254ece98c46a7e22a6fb5d4aa
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.content.ActivityNotFoundException;
22import android.content.Context;
23import android.content.ContentResolver;
24import android.content.DialogInterface;
25import android.content.Intent;
26import android.graphics.Bitmap;
27import android.graphics.BitmapFactory;
28import android.graphics.Matrix;
29import android.hardware.Camera;
30import android.hardware.Camera.Parameters;
31import android.hardware.Camera.Size;
32import android.net.Uri;
33import android.os.ParcelFileDescriptor;
34import android.telephony.TelephonyManager;
35import android.util.Log;
36import android.view.Display;
37import android.view.Surface;
38import android.view.View;
39import android.view.animation.Animation;
40import android.view.animation.TranslateAnimation;
41
42import java.io.Closeable;
43import java.io.IOException;
44import java.lang.reflect.Method;
45import java.util.List;
46import java.util.StringTokenizer;
47
48/**
49 * Collection of utility functions used in this package.
50 */
51public class Util {
52    private static final String TAG = "Util";
53    private static final int DIRECTION_LEFT = 0;
54    private static final int DIRECTION_RIGHT = 1;
55    private static final int DIRECTION_UP = 2;
56    private static final int DIRECTION_DOWN = 3;
57
58    public static final String REVIEW_ACTION = "com.android.camera.action.REVIEW";
59
60    // Private intent extras. Test only.
61    private static final String EXTRAS_CAMERA_FACING =
62            "android.intent.extras.CAMERA_FACING";
63
64    private Util() {
65    }
66
67    // Rotates the bitmap by the specified degree.
68    // If a new bitmap is created, the original bitmap is recycled.
69    public static Bitmap rotate(Bitmap b, int degrees) {
70        return rotateAndMirror(b, degrees, false);
71    }
72
73    // Rotates and/or mirrors the bitmap. If a new bitmap is created, the
74    // original bitmap is recycled.
75    public static Bitmap rotateAndMirror(Bitmap b, int degrees, boolean mirror) {
76        if ((degrees != 0 || mirror) && b != null) {
77            Matrix m = new Matrix();
78            m.setRotate(degrees,
79                    (float) b.getWidth() / 2, (float) b.getHeight() / 2);
80            if (mirror) {
81                m.postScale(-1, 1);
82                degrees = (degrees + 360) % 360;
83                if (degrees == 0 || degrees == 180) {
84                    m.postTranslate((float) b.getWidth(), 0);
85                } else if (degrees == 90 || degrees == 270) {
86                    m.postTranslate((float) b.getHeight(), 0);
87                } else {
88                    throw new IllegalArgumentException("Invalid degrees=" + degrees);
89                }
90            }
91
92            try {
93                Bitmap b2 = Bitmap.createBitmap(
94                        b, 0, 0, b.getWidth(), b.getHeight(), m, true);
95                if (b != b2) {
96                    b.recycle();
97                    b = b2;
98                }
99            } catch (OutOfMemoryError ex) {
100                // We have no memory to rotate. Return the original bitmap.
101            }
102        }
103        return b;
104    }
105
106    /*
107     * Compute the sample size as a function of minSideLength
108     * and maxNumOfPixels.
109     * minSideLength is used to specify that minimal width or height of a
110     * bitmap.
111     * maxNumOfPixels is used to specify the maximal size in pixels that is
112     * tolerable in terms of memory usage.
113     *
114     * The function returns a sample size based on the constraints.
115     * Both size and minSideLength can be passed in as -1
116     * which indicates no care of the corresponding constraint.
117     * The functions prefers returning a sample size that
118     * generates a smaller bitmap, unless minSideLength = -1.
119     *
120     * Also, the function rounds up the sample size to a power of 2 or multiple
121     * of 8 because BitmapFactory only honors sample size this way.
122     * For example, BitmapFactory downsamples an image by 2 even though the
123     * request is 3. So we round up the sample size to avoid OOM.
124     */
125    public static int computeSampleSize(BitmapFactory.Options options,
126            int minSideLength, int maxNumOfPixels) {
127        int initialSize = computeInitialSampleSize(options, minSideLength,
128                maxNumOfPixels);
129
130        int roundedSize;
131        if (initialSize <= 8) {
132            roundedSize = 1;
133            while (roundedSize < initialSize) {
134                roundedSize <<= 1;
135            }
136        } else {
137            roundedSize = (initialSize + 7) / 8 * 8;
138        }
139
140        return roundedSize;
141    }
142
143    private static int computeInitialSampleSize(BitmapFactory.Options options,
144            int minSideLength, int maxNumOfPixels) {
145        double w = options.outWidth;
146        double h = options.outHeight;
147
148        int lowerBound = (maxNumOfPixels < 0) ? 1 :
149                (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
150        int upperBound = (minSideLength < 0) ? 128 :
151                (int) Math.min(Math.floor(w / minSideLength),
152                Math.floor(h / minSideLength));
153
154        if (upperBound < lowerBound) {
155            // return the larger one when there is no overlapping zone.
156            return lowerBound;
157        }
158
159        if (maxNumOfPixels < 0 && minSideLength < 0) {
160            return 1;
161        } else if (minSideLength < 0) {
162            return lowerBound;
163        } else {
164            return upperBound;
165        }
166    }
167
168    public static Bitmap makeBitmap(byte[] jpegData, int maxNumOfPixels) {
169        try {
170            BitmapFactory.Options options = new BitmapFactory.Options();
171            options.inJustDecodeBounds = true;
172            BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,
173                    options);
174            if (options.mCancel || options.outWidth == -1
175                    || options.outHeight == -1) {
176                return null;
177            }
178            options.inSampleSize = computeSampleSize(
179                    options, -1, maxNumOfPixels);
180            options.inJustDecodeBounds = false;
181
182            options.inDither = false;
183            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
184            return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,
185                    options);
186        } catch (OutOfMemoryError ex) {
187            Log.e(TAG, "Got oom exception ", ex);
188            return null;
189        }
190    }
191
192    public static void closeSilently(Closeable c) {
193        if (c == null) return;
194        try {
195            c.close();
196        } catch (Throwable t) {
197            // do nothing
198        }
199    }
200
201    public static void Assert(boolean cond) {
202        if (!cond) {
203            throw new AssertionError();
204        }
205    }
206
207    public static void showFatalErrorAndFinish(
208            final Activity activity, String title, String message) {
209        DialogInterface.OnClickListener buttonListener =
210                new DialogInterface.OnClickListener() {
211            public void onClick(DialogInterface dialog, int which) {
212                activity.finish();
213            }
214        };
215        new AlertDialog.Builder(activity)
216                .setCancelable(false)
217                .setIconAttribute(android.R.attr.alertDialogIcon)
218                .setTitle(title)
219                .setMessage(message)
220                .setNeutralButton(R.string.details_ok, buttonListener)
221                .show();
222    }
223
224    public static <T> T checkNotNull(T object) {
225        if (object == null) throw new NullPointerException();
226        return object;
227    }
228
229    public static boolean equals(Object a, Object b) {
230        return (a == b) || (a == null ? false : a.equals(b));
231    }
232
233    public static int nextPowerOf2(int n) {
234        n -= 1;
235        n |= n >>> 16;
236        n |= n >>> 8;
237        n |= n >>> 4;
238        n |= n >>> 2;
239        n |= n >>> 1;
240        return n + 1;
241    }
242
243    public static float distance(float x, float y, float sx, float sy) {
244        float dx = x - sx;
245        float dy = y - sy;
246        return (float) Math.sqrt(dx * dx + dy * dy);
247    }
248
249    public static int clamp(int x, int min, int max) {
250        if (x > max) return max;
251        if (x < min) return min;
252        return x;
253    }
254
255    public static int getDisplayRotation(Activity activity) {
256        int rotation = activity.getWindowManager().getDefaultDisplay()
257                .getRotation();
258        switch (rotation) {
259            case Surface.ROTATION_0: return 0;
260            case Surface.ROTATION_90: return 90;
261            case Surface.ROTATION_180: return 180;
262            case Surface.ROTATION_270: return 270;
263        }
264        return 0;
265    }
266
267    public static void setCameraDisplayOrientation(int degrees,
268            int cameraId, Camera camera) {
269        // See android.hardware.Camera.setCameraDisplayOrientation for
270        // documentation.
271        Camera.CameraInfo info = new Camera.CameraInfo();
272        Camera.getCameraInfo(cameraId, info);
273        int result;
274        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
275            result = (info.orientation + degrees) % 360;
276            result = (360 - result) % 360;  // compensate the mirror
277        } else {  // back-facing
278            result = (info.orientation - degrees + 360) % 360;
279        }
280        camera.setDisplayOrientation(result);
281    }
282
283    public static Size getOptimalPreviewSize(Activity currentActivity,
284            List<Size> sizes, double targetRatio) {
285        // Use a very small tolerance because we want an exact match.
286        final double ASPECT_TOLERANCE = 0.001;
287        if (sizes == null) return null;
288
289        Size optimalSize = null;
290        double minDiff = Double.MAX_VALUE;
291
292        // Because of bugs of overlay and layout, we sometimes will try to
293        // layout the viewfinder in the portrait orientation and thus get the
294        // wrong size of mSurfaceView. When we change the preview size, the
295        // new overlay will be created before the old one closed, which causes
296        // an exception. For now, just get the screen size
297
298        Display display = currentActivity.getWindowManager().getDefaultDisplay();
299        int targetHeight = Math.min(display.getHeight(), display.getWidth());
300
301        if (targetHeight <= 0) {
302            // We don't know the size of SurfaceView, use screen height
303            targetHeight = display.getHeight();
304        }
305
306        // Try to find an size match aspect ratio and size
307        for (Size size : sizes) {
308            double ratio = (double) size.width / size.height;
309            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
310            if (Math.abs(size.height - targetHeight) < minDiff) {
311                optimalSize = size;
312                minDiff = Math.abs(size.height - targetHeight);
313            }
314        }
315
316        // Cannot find the one match the aspect ratio. This should not happen.
317        // Ignore the requirement.
318        if (optimalSize == null) {
319            Log.w(TAG, "No preview size match the aspect ratio");
320            minDiff = Double.MAX_VALUE;
321            for (Size size : sizes) {
322                if (Math.abs(size.height - targetHeight) < minDiff) {
323                    optimalSize = size;
324                    minDiff = Math.abs(size.height - targetHeight);
325                }
326            }
327        }
328        return optimalSize;
329    }
330
331    public static void dumpParameters(Parameters parameters) {
332        String flattened = parameters.flatten();
333        StringTokenizer tokenizer = new StringTokenizer(flattened, ";");
334        Log.d(TAG, "Dump all camera parameters:");
335        while (tokenizer.hasMoreElements()) {
336            Log.d(TAG, tokenizer.nextToken());
337        }
338    }
339
340   /**
341     * Returns whether the device is voice-capable (meaning, it can do MMS).
342     */
343    public static boolean isMmsCapable(Context context) {
344        TelephonyManager telephonyManager = (TelephonyManager)
345                context.getSystemService(Context.TELEPHONY_SERVICE);
346        if (telephonyManager == null) {
347            return false;
348        }
349
350        try {
351            Class partypes[] = new Class[0];
352            Method sIsVoiceCapable = TelephonyManager.class.getMethod(
353                    "isVoiceCapable", partypes);
354
355            Object arglist[] = new Object[0];
356            Object retobj = sIsVoiceCapable.invoke(telephonyManager, arglist);
357            return (Boolean) retobj;
358        } catch (java.lang.reflect.InvocationTargetException ite) {
359            // Failure, must be another device.
360            // Assume that it is voice capable.
361        } catch (IllegalAccessException iae) {
362            // Failure, must be an other device.
363            // Assume that it is voice capable.
364        } catch (NoSuchMethodException nsme) {
365        }
366        return true;
367    }
368
369    // This is for test only. Allow the camera to launch the specific camera.
370    public static int getCameraFacingIntentExtras(Activity currentActivity) {
371        int cameraId = -1;
372
373        int intentCameraId =
374                currentActivity.getIntent().getIntExtra(Util.EXTRAS_CAMERA_FACING, -1);
375
376        if (isFrontCameraIntent(intentCameraId)) {
377            // Check if the front camera exist
378            int frontCameraId = CameraHolder.instance().getFrontCameraId();
379            if (frontCameraId != -1) {
380                cameraId = frontCameraId;
381            }
382        } else if (isBackCameraIntent(intentCameraId)) {
383            // Check if the back camera exist
384            int backCameraId = CameraHolder.instance().getBackCameraId();
385            if (backCameraId != -1) {
386                cameraId = backCameraId;
387            }
388        }
389        return cameraId;
390    }
391
392    private static boolean isFrontCameraIntent(int intentCameraId) {
393        return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
394    }
395
396    private static boolean isBackCameraIntent(int intentCameraId) {
397        return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK);
398    }
399
400    private static int mLocation[] = new int[2];
401
402    // This method is not thread-safe.
403    public static boolean pointInView(float x, float y, View v) {
404        v.getLocationInWindow(mLocation);
405        return x >= mLocation[0] && x < (mLocation[0] + v.getWidth())
406                && y >= mLocation[1] && y < (mLocation[1] + v.getHeight());
407    }
408
409    public static boolean isUriValid(Uri uri, ContentResolver resolver) {
410        if (uri == null) return false;
411
412        try {
413            ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
414            if (pfd == null) {
415                Log.e(TAG, "Fail to open URI. URI=" + uri);
416                return false;
417            }
418            pfd.close();
419        } catch (IOException ex) {
420            return false;
421        }
422        return true;
423    }
424
425    public static void viewUri(Uri uri, Context context) {
426        if (!isUriValid(uri, context.getContentResolver())) {
427            Log.e(TAG, "Uri invalid. uri=" + uri);
428            return;
429        }
430
431        try {
432            context.startActivity(new Intent(Util.REVIEW_ACTION, uri));
433        } catch (ActivityNotFoundException ex) {
434            try {
435                context.startActivity(new Intent(Intent.ACTION_VIEW, uri));
436            } catch (ActivityNotFoundException e) {
437                Log.e(TAG, "review image fail. uri=" + uri, e);
438            }
439        }
440    }
441}
442