Util.java revision 9cfab4bc18b8d9d905263c687e19c06df885dca7
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 com.android.camera.gallery.IImage;
20
21import android.app.Activity;
22import android.app.AlertDialog;
23import android.content.DialogInterface;
24import android.graphics.Bitmap;
25import android.graphics.BitmapFactory;
26import android.graphics.Matrix;
27import android.hardware.Camera;
28import android.hardware.Camera.Size;
29import android.util.Log;
30import android.view.Display;
31import android.view.Surface;
32import android.view.View;
33import android.view.animation.Animation;
34import android.view.animation.TranslateAnimation;
35
36import java.io.Closeable;
37import java.util.List;
38
39/**
40 * Collection of utility functions used in this package.
41 */
42public class Util {
43    private static final String TAG = "Util";
44    public static final int DIRECTION_LEFT = 0;
45    public static final int DIRECTION_RIGHT = 1;
46    public static final int DIRECTION_UP = 2;
47    public static final int DIRECTION_DOWN = 3;
48
49    public static final String REVIEW_ACTION = "com.android.camera.action.REVIEW";
50
51    private Util() {
52    }
53
54    // Rotates the bitmap by the specified degree.
55    // If a new bitmap is created, the original bitmap is recycled.
56    public static Bitmap rotate(Bitmap b, int degrees) {
57        return rotateAndMirror(b, degrees, false);
58    }
59
60    // Rotates and/or mirrors the bitmap. If a new bitmap is created, the
61    // original bitmap is recycled.
62    public static Bitmap rotateAndMirror(Bitmap b, int degrees, boolean mirror) {
63        if ((degrees != 0 || mirror) && b != null) {
64            Matrix m = new Matrix();
65            m.setRotate(degrees,
66                    (float) b.getWidth() / 2, (float) b.getHeight() / 2);
67            if (mirror) {
68                m.postScale(-1, 1);
69                degrees = (degrees + 360) % 360;
70                if (degrees == 0 || degrees == 180) {
71                    m.postTranslate((float) b.getWidth(), 0);
72                } else if (degrees == 90 || degrees == 270) {
73                    m.postTranslate((float) b.getHeight(), 0);
74                } else {
75                    throw new IllegalArgumentException("Invalid degrees=" + degrees);
76                }
77            }
78
79            try {
80                Bitmap b2 = Bitmap.createBitmap(
81                        b, 0, 0, b.getWidth(), b.getHeight(), m, true);
82                if (b != b2) {
83                    b.recycle();
84                    b = b2;
85                }
86            } catch (OutOfMemoryError ex) {
87                // We have no memory to rotate. Return the original bitmap.
88            }
89        }
90        return b;
91    }
92
93    /*
94     * Compute the sample size as a function of minSideLength
95     * and maxNumOfPixels.
96     * minSideLength is used to specify that minimal width or height of a
97     * bitmap.
98     * maxNumOfPixels is used to specify the maximal size in pixels that is
99     * tolerable in terms of memory usage.
100     *
101     * The function returns a sample size based on the constraints.
102     * Both size and minSideLength can be passed in as IImage.UNCONSTRAINED,
103     * which indicates no care of the corresponding constraint.
104     * The functions prefers returning a sample size that
105     * generates a smaller bitmap, unless minSideLength = IImage.UNCONSTRAINED.
106     *
107     * Also, the function rounds up the sample size to a power of 2 or multiple
108     * of 8 because BitmapFactory only honors sample size this way.
109     * For example, BitmapFactory downsamples an image by 2 even though the
110     * request is 3. So we round up the sample size to avoid OOM.
111     */
112    public static int computeSampleSize(BitmapFactory.Options options,
113            int minSideLength, int maxNumOfPixels) {
114        int initialSize = computeInitialSampleSize(options, minSideLength,
115                maxNumOfPixels);
116
117        int roundedSize;
118        if (initialSize <= 8) {
119            roundedSize = 1;
120            while (roundedSize < initialSize) {
121                roundedSize <<= 1;
122            }
123        } else {
124            roundedSize = (initialSize + 7) / 8 * 8;
125        }
126
127        return roundedSize;
128    }
129
130    private static int computeInitialSampleSize(BitmapFactory.Options options,
131            int minSideLength, int maxNumOfPixels) {
132        double w = options.outWidth;
133        double h = options.outHeight;
134
135        int lowerBound = (maxNumOfPixels == IImage.UNCONSTRAINED) ? 1 :
136                (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
137        int upperBound = (minSideLength == IImage.UNCONSTRAINED) ? 128 :
138                (int) Math.min(Math.floor(w / minSideLength),
139                Math.floor(h / minSideLength));
140
141        if (upperBound < lowerBound) {
142            // return the larger one when there is no overlapping zone.
143            return lowerBound;
144        }
145
146        if ((maxNumOfPixels == IImage.UNCONSTRAINED) &&
147                (minSideLength == IImage.UNCONSTRAINED)) {
148            return 1;
149        } else if (minSideLength == IImage.UNCONSTRAINED) {
150            return lowerBound;
151        } else {
152            return upperBound;
153        }
154    }
155
156    public static <T>  int indexOf(T [] array, T s) {
157        for (int i = 0; i < array.length; i++) {
158            if (array[i].equals(s)) {
159                return i;
160            }
161        }
162        return -1;
163    }
164
165    public static void closeSilently(Closeable c) {
166        if (c == null) return;
167        try {
168            c.close();
169        } catch (Throwable t) {
170            // do nothing
171        }
172    }
173
174    public static Bitmap makeBitmap(byte[] jpegData, int maxNumOfPixels) {
175        try {
176            BitmapFactory.Options options = new BitmapFactory.Options();
177            options.inJustDecodeBounds = true;
178            BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,
179                    options);
180            if (options.mCancel || options.outWidth == -1
181                    || options.outHeight == -1) {
182                return null;
183            }
184            options.inSampleSize = computeSampleSize(
185                    options, IImage.UNCONSTRAINED, maxNumOfPixels);
186            options.inJustDecodeBounds = false;
187
188            options.inDither = false;
189            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
190            return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,
191                    options);
192        } catch (OutOfMemoryError ex) {
193            Log.e(TAG, "Got oom exception ", ex);
194            return null;
195        }
196    }
197
198    public static void Assert(boolean cond) {
199        if (!cond) {
200            throw new AssertionError();
201        }
202    }
203
204    public static void showFatalErrorAndFinish(
205            final Activity activity, String title, String message) {
206        DialogInterface.OnClickListener buttonListener =
207                new DialogInterface.OnClickListener() {
208            public void onClick(DialogInterface dialog, int which) {
209                activity.finish();
210            }
211        };
212        new AlertDialog.Builder(activity)
213                .setCancelable(false)
214                .setIcon(android.R.drawable.ic_dialog_alert)
215                .setTitle(title)
216                .setMessage(message)
217                .setNeutralButton(R.string.details_ok, buttonListener)
218                .show();
219    }
220
221    public static Animation slideOut(View view, int to) {
222        view.setVisibility(View.INVISIBLE);
223        Animation anim;
224        switch (to) {
225            case DIRECTION_LEFT:
226                anim = new TranslateAnimation(0, -view.getWidth(), 0, 0);
227                break;
228            case DIRECTION_RIGHT:
229                anim = new TranslateAnimation(0, view.getWidth(), 0, 0);
230                break;
231            case DIRECTION_UP:
232                anim = new TranslateAnimation(0, 0, 0, -view.getHeight());
233                break;
234            case DIRECTION_DOWN:
235                anim = new TranslateAnimation(0, 0, 0, view.getHeight());
236                break;
237            default:
238                throw new IllegalArgumentException(Integer.toString(to));
239        }
240        anim.setDuration(500);
241        view.startAnimation(anim);
242        return anim;
243    }
244
245    public static Animation slideIn(View view, int from) {
246        view.setVisibility(View.VISIBLE);
247        Animation anim;
248        switch (from) {
249            case DIRECTION_LEFT:
250                anim = new TranslateAnimation(-view.getWidth(), 0, 0, 0);
251                break;
252            case DIRECTION_RIGHT:
253                anim = new TranslateAnimation(view.getWidth(), 0, 0, 0);
254                break;
255            case DIRECTION_UP:
256                anim = new TranslateAnimation(0, 0, -view.getHeight(), 0);
257                break;
258            case DIRECTION_DOWN:
259                anim = new TranslateAnimation(0, 0, view.getHeight(), 0);
260                break;
261            default:
262                throw new IllegalArgumentException(Integer.toString(from));
263        }
264        anim.setDuration(500);
265        view.startAnimation(anim);
266        return anim;
267    }
268
269    public static <T> T checkNotNull(T object) {
270        if (object == null) throw new NullPointerException();
271        return object;
272    }
273
274    public static boolean equals(Object a, Object b) {
275        return (a == b) || (a == null ? false : a.equals(b));
276    }
277
278    public static boolean isPowerOf2(int n) {
279        return (n & -n) == n;
280    }
281
282    public static int nextPowerOf2(int n) {
283        n -= 1;
284        n |= n >>> 16;
285        n |= n >>> 8;
286        n |= n >>> 4;
287        n |= n >>> 2;
288        n |= n >>> 1;
289        return n + 1;
290    }
291
292    public static float distance(float x, float y, float sx, float sy) {
293        float dx = x - sx;
294        float dy = y - sy;
295        return (float) Math.sqrt(dx * dx + dy * dy);
296    }
297
298    public static int clamp(int x, int min, int max) {
299        if (x > max) return max;
300        if (x < min) return min;
301        return x;
302    }
303
304    public static int getDisplayRotation(Activity activity) {
305        int rotation = activity.getWindowManager().getDefaultDisplay()
306                .getRotation();
307        switch (rotation) {
308            case Surface.ROTATION_0: return 0;
309            case Surface.ROTATION_90: return 90;
310            case Surface.ROTATION_180: return 180;
311            case Surface.ROTATION_270: return 270;
312        }
313        return 0;
314    }
315
316    public static void setCameraDisplayOrientation(Activity activity,
317            int cameraId, Camera camera) {
318        // See android.hardware.Camera.setCameraDisplayOrientation for
319        // documentation.
320        Camera.CameraInfo info = new Camera.CameraInfo();
321        Camera.getCameraInfo(cameraId, info);
322        int degrees = getDisplayRotation(activity);
323        int result;
324        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
325            result = (info.orientation + degrees) % 360;
326            result = (360 - result) % 360;  // compensate the mirror
327        } else {  // back-facing
328            result = (info.orientation - degrees + 360) % 360;
329        }
330        camera.setDisplayOrientation(result);
331    }
332
333    public static Size getOptimalPreviewSize(Activity currentActivity,
334            List<Size> sizes, double targetRatio) {
335        final double ASPECT_TOLERANCE = 0.05;
336        if (sizes == null) return null;
337
338        Size optimalSize = null;
339        double minDiff = Double.MAX_VALUE;
340
341        // Because of bugs of overlay and layout, we sometimes will try to
342        // layout the viewfinder in the portrait orientation and thus get the
343        // wrong size of mSurfaceView. When we change the preview size, the
344        // new overlay will be created before the old one closed, which causes
345        // an exception. For now, just get the screen size
346
347        Display display = currentActivity.getWindowManager().getDefaultDisplay();
348        int targetHeight = Math.min(display.getHeight(), display.getWidth());
349
350        if (targetHeight <= 0) {
351            // We don't know the size of SurfaceView, use screen height
352            targetHeight = display.getHeight();
353        }
354
355        // Try to find an size match aspect ratio and size
356        for (Size size : sizes) {
357            double ratio = (double) size.width / size.height;
358            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
359            if (Math.abs(size.height - targetHeight) < minDiff) {
360                optimalSize = size;
361                minDiff = Math.abs(size.height - targetHeight);
362            }
363        }
364
365        // Cannot find the one match the aspect ratio, ignore the requirement
366        if (optimalSize == null) {
367            Log.v(TAG, "No preview size match the aspect ratio");
368            minDiff = Double.MAX_VALUE;
369            for (Size size : sizes) {
370                if (Math.abs(size.height - targetHeight) < minDiff) {
371                    optimalSize = size;
372                    minDiff = Math.abs(size.height - targetHeight);
373                }
374            }
375        }
376        return optimalSize;
377    }
378}
379