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