summaryrefslogtreecommitdiffstats
path: root/src/com/android/gallery3d/filtershow/crop/CropActivity.java
blob: 26659a60069bccc28cdbb832db0612f0563c928a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.gallery3d.filtershow.crop;

import android.app.ActionBar;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Toast;

import com.android.gallery3d.R;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Activity for cropping an image.
 */
public class CropActivity extends Activity {
    private static final String LOGTAG = "CropActivity";
    private CropExtras mCropExtras = null;
    private LoadBitmapTask mLoadBitmapTask = null;
    private SaveBitmapTask mSaveBitmapTask = null;
    private SetWallpaperTask mSetWallpaperTask = null;
    private Bitmap mOriginalBitmap = null;
    private CropView mCropView = null;
    private int mActiveBackgroundIO = 0;
    private Intent mResultIntent = null;
    private static final int SELECT_PICTURE = 1; // request code for picker
    private static final int DEFAULT_DENSITY = 133;
    private static final int DEFAULT_COMPRESS_QUALITY = 90;
    public static final int MAX_BMAP_IN_INTENT = 990000;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        mResultIntent = new Intent();
        setResult(RESULT_CANCELED, mResultIntent);
        mCropExtras = getExtrasFromIntent(intent);
        if (mCropExtras != null && mCropExtras.getShowWhenLocked()) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        }

        setContentView(R.layout.crop_activity);
        mCropView = (CropView) findViewById(R.id.cropView);

        if (intent.getData() != null) {
            startLoadBitmap(intent.getData());
        } else {
            pickImage();
        }
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setCustomView(R.layout.filtershow_actionbar);

        View saveButton = actionBar.getCustomView();
        saveButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                startFinishOutput();
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (mLoadBitmapTask != null) {
            mLoadBitmapTask.cancel(false);
        }
        super.onDestroy();
    }

    /**
     * Opens a selector in Gallery to chose an image for use when none was given
     * in the CROP intent.
     */
    public void pickImage() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, getString(R.string.select_image)),
                SELECT_PICTURE);
    }

    /**
     * Callback for pickImage().
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            startLoadBitmap(selectedImageUri);
        }
    }

    /**
     * Gets the crop extras from the intent, or null if none exist.
     */
    public static CropExtras getExtrasFromIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            return new CropExtras(extras.getInt(CropExtras.KEY_OUTPUT_X, 0),
                    extras.getInt(CropExtras.KEY_OUTPUT_Y, 0),
                    extras.getBoolean(CropExtras.KEY_SCALE, true) &&
                            extras.getBoolean(CropExtras.KEY_SCALE_UP_IF_NEEDED, false),
                    extras.getInt(CropExtras.KEY_ASPECT_X, 0),
                    extras.getInt(CropExtras.KEY_ASPECT_Y, 0),
                    extras.getBoolean(CropExtras.KEY_SET_AS_WALLPAPER, false),
                    extras.getBoolean(CropExtras.KEY_RETURN_DATA, false),
                    (Uri) extras.getParcelable(MediaStore.EXTRA_OUTPUT),
                    extras.getString(CropExtras.KEY_OUTPUT_FORMAT),
                    extras.getBoolean(CropExtras.KEY_SHOW_WHEN_LOCKED, false),
                    extras.getFloat(CropExtras.KEY_SPOTLIGHT_X),
                    extras.getFloat(CropExtras.KEY_SPOTLIGHT_Y));
        }
        return null;
    }

    /**
     * Gets screen size metric.
     */
    private int getScreenImageSize() {
        DisplayMetrics metrics = new DisplayMetrics();
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        display.getMetrics(metrics);
        int msize = Math.min(size.x, size.y);
        // TODO: WTF
        return (DEFAULT_DENSITY * msize) / metrics.densityDpi + 512;
    }

    /**
     * Method that loads a bitmap in an async task.
     */
    private void startLoadBitmap(Uri uri) {
        mActiveBackgroundIO++;
        final View loading = findViewById(R.id.loading);
        loading.setVisibility(View.VISIBLE);
        mLoadBitmapTask = new LoadBitmapTask();
        mLoadBitmapTask.execute(uri);
    }

    /**
     * Method called on UI thread with loaded bitmap.
     */
    private void doneLoadBitmap(Bitmap bitmap) {
        mActiveBackgroundIO--;
        final View loading = findViewById(R.id.loading);
        loading.setVisibility(View.GONE);
        mOriginalBitmap = bitmap;
        // TODO: move these to dimens folder
        if (bitmap != null) {
            mCropView.setup(bitmap, (int) getPixelsFromDip(55), (int) getPixelsFromDip(25));
        } else {
            Log.w(LOGTAG, "could not load image for cropping");
            cannotLoadImage();
            setResult(RESULT_CANCELED, mResultIntent);
            done();
        }
    }

    /**
     * Display toast for image loading failure.
     */
    private void cannotLoadImage() {
        CharSequence text = getString(R.string.cannot_load_image);
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        toast.show();
    }

    /**
     * AsyncTask for loading a bitmap into memory.
     *
     * @see #startLoadBitmap(Uri)
     * @see #doneLoadBitmap(Bitmap)
     */
    private class LoadBitmapTask extends AsyncTask<Uri, Void, Bitmap> {
        int mBitmapSize;
        Context mContext;
        Rect mOriginalBounds;

        public LoadBitmapTask() {
            mBitmapSize = getScreenImageSize();
            Log.v(LOGTAG, "bitmap size: " + mBitmapSize);
            mContext = getApplicationContext();
            mOriginalBounds = new Rect();
        }

        @Override
        protected Bitmap doInBackground(Uri... params) {
            Bitmap bmap = CropLoader.getConstrainedBitmap(params[0], mContext, mBitmapSize,
                    mOriginalBounds);
            return bmap;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            doneLoadBitmap(result);
            // super.onPostExecute(result);
        }
    }

    private void startSaveBitmap(Bitmap bmap, Uri uri, String format) {
        if (bmap == null || uri == null) {
            throw new IllegalArgumentException("bad argument to startSaveBitmap");
        }
        mActiveBackgroundIO++;
        final View loading = findViewById(R.id.loading);
        loading.setVisibility(View.VISIBLE);
        mSaveBitmapTask = new SaveBitmapTask(uri, format);
        mSaveBitmapTask.execute(bmap);
    }

    private void doneSaveBitmap(Uri uri) {
        mActiveBackgroundIO--;
        final View loading = findViewById(R.id.loading);
        loading.setVisibility(View.GONE);
        if (uri == null) {
            Log.w(LOGTAG, "failed to save bitmap");
            setResult(RESULT_CANCELED, mResultIntent);
            done();
            return;
        }
        done();
    }

    private class SaveBitmapTask extends AsyncTask<Bitmap, Void, Boolean> {

        OutputStream mOutStream = null;
        String mOutputFormat = null;
        Uri mOutUri = null;

        public SaveBitmapTask(Uri uri, String outputFormat) {
            mOutputFormat = outputFormat;
            mOutStream = null;
            mOutUri = uri;
            try {
                mOutStream = getContentResolver().openOutputStream(uri);
            } catch (FileNotFoundException e) {
                Log.w(LOGTAG, "cannot write output: " + mOutUri.toString(), e);
            }
        }

        @Override
        protected Boolean doInBackground(Bitmap... params) {
            if (mOutStream == null) {
                return false;
            }
            CompressFormat cf = convertExtensionToCompressFormat(getFileExtension(mOutputFormat));
            return params[0].compress(cf, DEFAULT_COMPRESS_QUALITY, mOutStream);
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (result.booleanValue() == false) {
                Log.w(LOGTAG, "could not compress to output: " + mOutUri.toString());
                doneSaveBitmap(null);
            }
            doneSaveBitmap(mOutUri);
        }
    }

    private void startSetWallpaper(Bitmap bmap) {
        if (bmap == null) {
            throw new IllegalArgumentException("bad argument to startSetWallpaper");
        }
        mActiveBackgroundIO++;
        Toast.makeText(this, R.string.setting_wallpaper, Toast.LENGTH_LONG).show();
        mSetWallpaperTask = new SetWallpaperTask();
        mSetWallpaperTask.execute(bmap);

    }

    private void doneSetWallpaper() {
        mActiveBackgroundIO--;
        done();
    }

    private class SetWallpaperTask extends AsyncTask<Bitmap, Void, Boolean> {
        private final WallpaperManager mWPManager;

        public SetWallpaperTask() {
            mWPManager = WallpaperManager.getInstance(getApplicationContext());
        }

        @Override
        protected Boolean doInBackground(Bitmap... params) {
            try {
                mWPManager.setBitmap(params[0]);
            } catch (IOException e) {
                Log.w(LOGTAG, "fail to set wall paper", e);
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            doneSetWallpaper();
        }
    }

    private void startFinishOutput() {
        if (mOriginalBitmap != null && mCropExtras != null) {
            Bitmap cropped = null;
            if (mCropExtras.getExtraOutput() != null) {
                if (cropped == null) {
                    cropped = getCroppedImage(mOriginalBitmap);
                }
                startSaveBitmap(cropped, mCropExtras.getExtraOutput(),
                        mCropExtras.getOutputFormat());
            }
            if (mCropExtras.getSetAsWallpaper()) {
                if (cropped == null) {
                    cropped = getCroppedImage(mOriginalBitmap);
                }
                startSetWallpaper(cropped);
            }
            if (mCropExtras.getReturnData()) {
                if (cropped == null) {
                    cropped = getCroppedImage(mOriginalBitmap);
                }
                int bmapSize = cropped.getRowBytes() * cropped.getHeight();
                if (bmapSize > MAX_BMAP_IN_INTENT) {
                    Log.w(LOGTAG, "Bitmap too large to be returned via intent");
                } else {
                    mResultIntent.putExtra(CropExtras.KEY_DATA, cropped);
                }
            }
            setResult(RESULT_OK, mResultIntent);
        } else {
            setResult(RESULT_CANCELED, mResultIntent);
        }
        done();
    }

    private void done() {
        if (mActiveBackgroundIO == 0) {
            finish();
        }
    }

    private Bitmap getCroppedImage(Bitmap image) {
        RectF imageBounds = new RectF(0, 0, image.getWidth(), image.getHeight());
        RectF crop = getBitmapCrop(imageBounds);
        if (crop == null) {
            return image;
        }
        Rect intCrop = new Rect();
        crop.roundOut(intCrop);
        return Bitmap.createBitmap(image, intCrop.left, intCrop.top, intCrop.width(),
                intCrop.height());
    }

    private RectF getBitmapCrop(RectF imageBounds) {
        RectF crop = new RectF();
        if (!mCropView.getCropBounds(crop, imageBounds)) {
            Log.w(LOGTAG, "could not get crop");
            return null;
        }
        return crop;
    }

    /**
     * Helper method for unit conversions.
     */
    public float getPixelsFromDip(float value) {
        Resources r = getResources();
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value,
                r.getDisplayMetrics());
    }

    private static CompressFormat convertExtensionToCompressFormat(String extension) {
        return extension.equals("png") ? CompressFormat.PNG : CompressFormat.JPEG;
    }

    private static String getFileExtension(String requestFormat) {
        String outputFormat = (requestFormat == null)
                ? "jpg"
                : requestFormat;
        outputFormat = outputFormat.toLowerCase();
        return (outputFormat.equals("png") || outputFormat.equals("gif"))
                ? "png" // We don't support gif compression.
                : "jpg";
    }

}