Util.java revision 2c6c6174e2363fccb4e4f29b76290e99234fe140
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.ProgressDialog;
22import android.content.ContentResolver;
23import android.content.DialogInterface;
24import android.content.Intent;
25import android.graphics.Bitmap;
26import android.graphics.BitmapFactory;
27import android.graphics.Canvas;
28import android.graphics.Matrix;
29import android.graphics.Rect;
30import android.media.MediaMetadataRetriever;
31import android.net.Uri;
32import android.os.Handler;
33import android.os.ParcelFileDescriptor;
34import android.util.Log;
35import android.view.View;
36import android.view.View.OnClickListener;
37import android.view.animation.Animation;
38import android.view.animation.TranslateAnimation;
39
40import com.android.camera.gallery.IImage;
41
42import java.io.ByteArrayOutputStream;
43import java.io.Closeable;
44import java.io.FileDescriptor;
45import java.io.IOException;
46
47/**
48 * Collection of utility functions used in this package.
49 */
50public class Util {
51    private static final String TAG = "Util";
52    public static final int DIRECTION_LEFT = 0;
53    public static final int DIRECTION_RIGHT = 1;
54    public static final int DIRECTION_UP = 2;
55    public static final int DIRECTION_DOWN = 3;
56
57    private static OnClickListener sNullOnClickListener;
58
59    private Util() {
60    }
61
62    // Rotates the bitmap by the specified degree.
63    // If a new bitmap is created, the original bitmap is recycled.
64    public static Bitmap rotate(Bitmap b, int degrees) {
65        if (degrees != 0 && b != null) {
66            Matrix m = new Matrix();
67            m.setRotate(degrees,
68                    (float) b.getWidth() / 2, (float) b.getHeight() / 2);
69            try {
70                Bitmap b2 = Bitmap.createBitmap(
71                        b, 0, 0, b.getWidth(), b.getHeight(), m, true);
72                if (b != b2) {
73                    b.recycle();
74                    b = b2;
75                }
76            } catch (OutOfMemoryError ex) {
77                // We have no memory to rotate. Return the original bitmap.
78            }
79        }
80        return b;
81    }
82
83    /*
84     * Compute the sample size as a function of minSideLength
85     * and maxNumOfPixels.
86     * minSideLength is used to specify that minimal width or height of a
87     * bitmap.
88     * maxNumOfPixels is used to specify the maximal size in pixels that is
89     * tolerable in terms of memory usage.
90     *
91     * The function returns a sample size based on the constraints.
92     * Both size and minSideLength can be passed in as IImage.UNCONSTRAINED,
93     * which indicates no care of the corresponding constraint.
94     * The functions prefers returning a sample size that
95     * generates a smaller bitmap, unless minSideLength = IImage.UNCONSTRAINED.
96     *
97     * Also, the function rounds up the sample size to a power of 2 or multiple
98     * of 8 because BitmapFactory only honors sample size this way.
99     * For example, BitmapFactory downsamples an image by 2 even though the
100     * request is 3. So we round up the sample size to avoid OOM.
101     */
102    public static int computeSampleSize(BitmapFactory.Options options,
103            int minSideLength, int maxNumOfPixels) {
104        int initialSize = computeInitialSampleSize(options, minSideLength,
105                maxNumOfPixels);
106
107        int roundedSize;
108        if (initialSize <= 8) {
109            roundedSize = 1;
110            while (roundedSize < initialSize) {
111                roundedSize <<= 1;
112            }
113        } else {
114            roundedSize = (initialSize + 7) / 8 * 8;
115        }
116
117        return roundedSize;
118    }
119
120    private static int computeInitialSampleSize(BitmapFactory.Options options,
121            int minSideLength, int maxNumOfPixels) {
122        double w = options.outWidth;
123        double h = options.outHeight;
124
125        int lowerBound = (maxNumOfPixels == IImage.UNCONSTRAINED) ? 1 :
126                (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
127        int upperBound = (minSideLength == IImage.UNCONSTRAINED) ? 128 :
128                (int) Math.min(Math.floor(w / minSideLength),
129                Math.floor(h / minSideLength));
130
131        if (upperBound < lowerBound) {
132            // return the larger one when there is no overlapping zone.
133            return lowerBound;
134        }
135
136        if ((maxNumOfPixels == IImage.UNCONSTRAINED) &&
137                (minSideLength == IImage.UNCONSTRAINED)) {
138            return 1;
139        } else if (minSideLength == IImage.UNCONSTRAINED) {
140            return lowerBound;
141        } else {
142            return upperBound;
143        }
144    }
145
146    // Whether we should recycle the input (unless the output is the input).
147    public static final boolean RECYCLE_INPUT = true;
148    public static final boolean NO_RECYCLE_INPUT = false;
149
150    public static Bitmap transform(Matrix scaler,
151                                   Bitmap source,
152                                   int targetWidth,
153                                   int targetHeight,
154                                   boolean scaleUp,
155                                   boolean recycle) {
156        int deltaX = source.getWidth() - targetWidth;
157        int deltaY = source.getHeight() - targetHeight;
158        if (!scaleUp && (deltaX < 0 || deltaY < 0)) {
159            /*
160             * In this case the bitmap is smaller, at least in one dimension,
161             * than the target.  Transform it by placing as much of the image
162             * as possible into the target and leaving the top/bottom or
163             * left/right (or both) black.
164             */
165            Bitmap b2 = Bitmap.createBitmap(targetWidth, targetHeight,
166                    Bitmap.Config.ARGB_8888);
167            Canvas c = new Canvas(b2);
168
169            int deltaXHalf = Math.max(0, deltaX / 2);
170            int deltaYHalf = Math.max(0, deltaY / 2);
171            Rect src = new Rect(
172                    deltaXHalf,
173                    deltaYHalf,
174                    deltaXHalf + Math.min(targetWidth, source.getWidth()),
175                    deltaYHalf + Math.min(targetHeight, source.getHeight()));
176            int dstX = (targetWidth  - src.width())  / 2;
177            int dstY = (targetHeight - src.height()) / 2;
178            Rect dst = new Rect(
179                    dstX,
180                    dstY,
181                    targetWidth - dstX,
182                    targetHeight - dstY);
183            c.drawBitmap(source, src, dst, null);
184            if (recycle) {
185                source.recycle();
186            }
187            return b2;
188        }
189        float bitmapWidthF = source.getWidth();
190        float bitmapHeightF = source.getHeight();
191
192        float bitmapAspect = bitmapWidthF / bitmapHeightF;
193        float viewAspect   = (float) targetWidth / targetHeight;
194
195        if (bitmapAspect > viewAspect) {
196            float scale = targetHeight / bitmapHeightF;
197            if (scale < .9F || scale > 1F) {
198                scaler.setScale(scale, scale);
199            } else {
200                scaler = null;
201            }
202        } else {
203            float scale = targetWidth / bitmapWidthF;
204            if (scale < .9F || scale > 1F) {
205                scaler.setScale(scale, scale);
206            } else {
207                scaler = null;
208            }
209        }
210
211        Bitmap b1;
212        if (scaler != null) {
213            // this is used for minithumb and crop, so we want to filter here.
214            b1 = Bitmap.createBitmap(source, 0, 0,
215                    source.getWidth(), source.getHeight(), scaler, true);
216        } else {
217            b1 = source;
218        }
219
220        if (recycle && b1 != source) {
221            source.recycle();
222        }
223
224        int dx1 = Math.max(0, b1.getWidth() - targetWidth);
225        int dy1 = Math.max(0, b1.getHeight() - targetHeight);
226
227        Bitmap b2 = Bitmap.createBitmap(
228                b1,
229                dx1 / 2,
230                dy1 / 2,
231                targetWidth,
232                targetHeight);
233
234        if (b2 != b1) {
235            if (recycle || b1 != source) {
236                b1.recycle();
237            }
238        }
239
240        return b2;
241    }
242
243    /**
244     * Creates a centered bitmap of the desired size.
245     * @param source
246     * @param recycle whether we want to recycle the input
247     */
248    public static Bitmap extractMiniThumb(
249            Bitmap source, int width, int height, boolean recycle) {
250        if (source == null) {
251            return null;
252        }
253
254        float scale;
255        if (source.getWidth() < source.getHeight()) {
256            scale = width / (float) source.getWidth();
257        } else {
258            scale = height / (float) source.getHeight();
259        }
260        Matrix matrix = new Matrix();
261        matrix.setScale(scale, scale);
262        Bitmap miniThumbnail = transform(matrix, source, width, height,
263                false, recycle);
264        return miniThumbnail;
265    }
266
267    /**
268     * Creates a byte[] for a given bitmap of the desired size. Recycles the
269     * input bitmap.
270     */
271    public static byte[] miniThumbData(Bitmap source) {
272        if (source == null) return null;
273
274        Bitmap miniThumbnail = extractMiniThumb(
275                source, IImage.MINI_THUMB_TARGET_SIZE,
276                IImage.MINI_THUMB_TARGET_SIZE,
277                Util.RECYCLE_INPUT);
278
279        ByteArrayOutputStream miniOutStream = new ByteArrayOutputStream();
280        miniThumbnail.compress(Bitmap.CompressFormat.JPEG, 75, miniOutStream);
281        miniThumbnail.recycle();
282
283        try {
284            miniOutStream.close();
285            byte [] data = miniOutStream.toByteArray();
286            return data;
287        } catch (java.io.IOException ex) {
288            Log.e(TAG, "got exception ex " + ex);
289        }
290        return null;
291    }
292
293    /**
294     * Create a video thumbnail for a video. May return null if the video is
295     * corrupt.
296     *
297     * @param filePath
298     */
299    public static Bitmap createVideoThumbnail(String filePath) {
300        Bitmap bitmap = null;
301        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
302        try {
303            retriever.setMode(MediaMetadataRetriever.MODE_CAPTURE_FRAME_ONLY);
304            retriever.setDataSource(filePath);
305            bitmap = retriever.captureFrame();
306        } catch (IllegalArgumentException ex) {
307            // Assume this is a corrupt video file
308        } catch (RuntimeException ex) {
309            // Assume this is a corrupt video file.
310        } finally {
311            try {
312                retriever.release();
313            } catch (RuntimeException ex) {
314                // Ignore failures while cleaning up.
315            }
316        }
317        return bitmap;
318    }
319
320    public static <T>  int indexOf(T [] array, T s) {
321        for (int i = 0; i < array.length; i++) {
322            if (array[i].equals(s)) {
323                return i;
324            }
325        }
326        return -1;
327    }
328
329    public static void closeSilently(Closeable c) {
330        if (c == null) return;
331        try {
332            c.close();
333        } catch (Throwable t) {
334            // do nothing
335        }
336    }
337
338    public static void closeSilently(ParcelFileDescriptor c) {
339        if (c == null) return;
340        try {
341            c.close();
342        } catch (Throwable t) {
343            // do nothing
344        }
345    }
346
347    /**
348     * Make a bitmap from a given Uri.
349     *
350     * @param uri
351     */
352    public static Bitmap makeBitmap(int minSideLength, int maxNumOfPixels,
353            Uri uri, ContentResolver cr) {
354        return makeBitmap(minSideLength, maxNumOfPixels, uri, cr,
355                IImage.NO_NATIVE);
356    }
357
358    public static Bitmap makeBitmap(int minSideLength, int maxNumOfPixels,
359            Uri uri, ContentResolver cr, boolean useNative) {
360        ParcelFileDescriptor input = null;
361        try {
362            input = cr.openFileDescriptor(uri, "r");
363            BitmapFactory.Options options = null;
364            if (useNative) {
365                options = createNativeAllocOptions();
366            }
367            return makeBitmap(minSideLength, maxNumOfPixels, uri, cr, input,
368                    options);
369        } catch (IOException ex) {
370            return null;
371        } finally {
372            closeSilently(input);
373        }
374    }
375
376    public static Bitmap makeBitmap(int minSideLength, int maxNumOfPixels,
377            ParcelFileDescriptor pfd, boolean useNative) {
378        BitmapFactory.Options options = null;
379        if (useNative) {
380            options = createNativeAllocOptions();
381        }
382        return makeBitmap(minSideLength, maxNumOfPixels, null, null, pfd,
383                options);
384    }
385
386    public static Bitmap makeBitmap(int minSideLength, int maxNumOfPixels,
387            Uri uri, ContentResolver cr, ParcelFileDescriptor pfd,
388            BitmapFactory.Options options) {
389        Bitmap b = null;
390        try {
391            if (pfd == null) pfd = makeInputStream(uri, cr);
392            if (pfd == null) return null;
393            if (options == null) options = new BitmapFactory.Options();
394
395            FileDescriptor fd = pfd.getFileDescriptor();
396            options.inSampleSize = 1;
397            options.inJustDecodeBounds = true;
398            BitmapManager.instance().decodeFileDescriptor(fd, options);
399            if (options.mCancel || options.outWidth == -1
400                    || options.outHeight == -1) {
401                return null;
402            }
403            options.inSampleSize = computeSampleSize(
404                    options, minSideLength, maxNumOfPixels);
405            options.inJustDecodeBounds = false;
406
407            options.inDither = false;
408            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
409            b = BitmapManager.instance().decodeFileDescriptor(fd, options);
410        } catch (OutOfMemoryError ex) {
411            Log.e(TAG, "Got oom exception ", ex);
412            return null;
413        } finally {
414            closeSilently(pfd);
415        }
416        return b;
417    }
418
419    private static ParcelFileDescriptor makeInputStream(
420            Uri uri, ContentResolver cr) {
421        try {
422            return cr.openFileDescriptor(uri, "r");
423        } catch (IOException ex) {
424            return null;
425        }
426    }
427
428    public static synchronized OnClickListener getNullOnClickListener() {
429        if (sNullOnClickListener == null) {
430            sNullOnClickListener = new OnClickListener() {
431                public void onClick(View v) {
432                }
433            };
434        }
435        return sNullOnClickListener;
436    }
437
438    public static void Assert(boolean cond) {
439        if (!cond) {
440            throw new AssertionError();
441        }
442    }
443
444    public static boolean equals(String a, String b) {
445        // return true if both string are null or the content equals
446        return a == b || a.equals(b);
447    }
448
449    private static class BackgroundJob
450            extends MonitoredActivity.LifeCycleAdapter implements Runnable {
451
452        private final MonitoredActivity mActivity;
453        private final ProgressDialog mDialog;
454        private final Runnable mJob;
455        private final Handler mHandler;
456        private final Runnable mCleanupRunner = new Runnable() {
457            public void run() {
458                mActivity.removeLifeCycleListener(BackgroundJob.this);
459                if (mDialog.getWindow() != null) mDialog.dismiss();
460            }
461        };
462
463        public BackgroundJob(MonitoredActivity activity, Runnable job,
464                ProgressDialog dialog, Handler handler) {
465            mActivity = activity;
466            mDialog = dialog;
467            mJob = job;
468            mActivity.addLifeCycleListener(this);
469            mHandler = handler;
470        }
471
472        public void run() {
473            try {
474                mJob.run();
475            } finally {
476                mHandler.post(mCleanupRunner);
477            }
478        }
479
480
481        @Override
482        public void onActivityDestroyed(MonitoredActivity activity) {
483            // We get here only when the onDestroyed being called before
484            // the mCleanupRunner. So, run it now and remove it from the queue
485            mCleanupRunner.run();
486            mHandler.removeCallbacks(mCleanupRunner);
487        }
488
489        @Override
490        public void onActivityStopped(MonitoredActivity activity) {
491            mDialog.hide();
492        }
493
494        @Override
495        public void onActivityStarted(MonitoredActivity activity) {
496            mDialog.show();
497        }
498    }
499
500    public static void startBackgroundJob(MonitoredActivity activity,
501            String title, String message, Runnable job, Handler handler) {
502        // Make the progress dialog uncancelable, so that we can gurantee
503        // the thread will be done before the activity getting destroyed.
504        ProgressDialog dialog = ProgressDialog.show(
505                activity, title, message, true, false);
506        new Thread(new BackgroundJob(activity, job, dialog, handler)).start();
507    }
508
509    // Returns an intent which is used for "set as" menu items.
510    public static Intent createSetAsIntent(IImage image) {
511        Uri u = image.fullSizeImageUri();
512        Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
513        intent.setDataAndType(u, image.getMimeType());
514        intent.putExtra("mimeType", image.getMimeType());
515        return intent;
516    }
517
518    // Returns Options that set the puregeable flag for Bitmap decode.
519    public static BitmapFactory.Options createNativeAllocOptions() {
520        BitmapFactory.Options options = new BitmapFactory.Options();
521        options.inNativeAlloc = true;
522        return options;
523    }
524
525    public static void showFatalErrorAndFinish(
526            final Activity activity, String title, String message) {
527        DialogInterface.OnClickListener buttonListener =
528                new DialogInterface.OnClickListener() {
529            public void onClick(DialogInterface dialog, int which) {
530                activity.finish();
531            }
532        };
533        new AlertDialog.Builder(activity)
534                .setCancelable(false)
535                .setIcon(android.R.drawable.ic_dialog_alert)
536                .setTitle(title)
537                .setMessage(message)
538                .setNeutralButton(R.string.details_ok, buttonListener)
539                .show();
540    }
541
542    public static void slideOut(View view, int to) {
543        view.setVisibility(View.INVISIBLE);
544        Animation anim;
545        switch (to) {
546            case DIRECTION_LEFT:
547                anim = new TranslateAnimation(0, -view.getWidth(), 0, 0);
548                break;
549            case DIRECTION_RIGHT:
550                anim = new TranslateAnimation(0, view.getWidth(), 0, 0);
551                break;
552            case DIRECTION_UP:
553                anim = new TranslateAnimation(0, 0, 0, -view.getHeight());
554                break;
555            case DIRECTION_DOWN:
556                anim = new TranslateAnimation(0, 0, 0, view.getHeight());
557                break;
558            default:
559                throw new IllegalArgumentException(Integer.toString(to));
560        }
561        anim.setDuration(500);
562        view.startAnimation(anim);
563    }
564
565    public static void slideIn(View view, int from) {
566        view.setVisibility(View.VISIBLE);
567        Animation anim;
568        switch (from) {
569            case DIRECTION_LEFT:
570                anim = new TranslateAnimation(-view.getWidth(), 0, 0, 0);
571                break;
572            case DIRECTION_RIGHT:
573                anim = new TranslateAnimation(view.getWidth(), 0, 0, 0);
574                break;
575            case DIRECTION_UP:
576                anim = new TranslateAnimation(0, 0, -view.getHeight(), 0);
577                break;
578            case DIRECTION_DOWN:
579                anim = new TranslateAnimation(0, 0, view.getHeight(), 0);
580                break;
581            default:
582                throw new IllegalArgumentException(Integer.toString(from));
583        }
584        anim.setDuration(500);
585        view.startAnimation(anim);
586    }
587
588    public static <T> T checkNotNull(T object) {
589        if (object == null) throw new NullPointerException();
590        return object;
591    }
592}
593