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