FilterShowActivity.java revision f79f954f4eb23bce55061c683a07fc7b3a965451
1/*
2 * Copyright (C) 2012 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.gallery3d.filtershow;
18
19import android.app.ActionBar;
20import android.app.Activity;
21import android.app.ProgressDialog;
22import android.app.WallpaperManager;
23import android.content.ContentValues;
24import android.content.Context;
25import android.content.Intent;
26import android.content.res.Configuration;
27import android.content.res.Resources;
28import android.graphics.Bitmap;
29import android.graphics.Color;
30import android.graphics.Point;
31import android.graphics.drawable.Drawable;
32import android.net.Uri;
33import android.os.AsyncTask;
34import android.os.Bundle;
35import android.provider.MediaStore;
36import android.util.DisplayMetrics;
37import android.util.Log;
38import android.util.TypedValue;
39import android.view.*;
40import android.view.View.OnClickListener;
41import android.widget.AdapterView;
42import android.widget.AdapterView.OnItemClickListener;
43import android.widget.FrameLayout;
44import android.widget.ImageButton;
45import android.widget.LinearLayout;
46import android.widget.ListView;
47import android.widget.ShareActionProvider;
48import android.widget.ShareActionProvider.OnShareTargetSelectedListener;
49import android.widget.Toast;
50
51import com.android.gallery3d.R;
52import com.android.gallery3d.data.LocalAlbum;
53import com.android.gallery3d.filtershow.cache.FilteringPipeline;
54import com.android.gallery3d.filtershow.cache.ImageLoader;
55import com.android.gallery3d.filtershow.editors.BasicEditor;
56import com.android.gallery3d.filtershow.editors.EditorCrop;
57import com.android.gallery3d.filtershow.editors.EditorDraw;
58import com.android.gallery3d.filtershow.editors.EditorFlip;
59import com.android.gallery3d.filtershow.editors.EditorInfo;
60import com.android.gallery3d.filtershow.editors.EditorManager;
61import com.android.gallery3d.filtershow.editors.EditorRedEye;
62import com.android.gallery3d.filtershow.editors.EditorRotate;
63import com.android.gallery3d.filtershow.editors.EditorStraighten;
64import com.android.gallery3d.filtershow.editors.EditorTinyPlanet;
65import com.android.gallery3d.filtershow.editors.ImageOnlyEditor;
66import com.android.gallery3d.filtershow.filters.*;
67import com.android.gallery3d.filtershow.imageshow.GeometryMetadata;
68import com.android.gallery3d.filtershow.imageshow.ImageCrop;
69import com.android.gallery3d.filtershow.imageshow.ImageShow;
70import com.android.gallery3d.filtershow.imageshow.ImageTinyPlanet;
71import com.android.gallery3d.filtershow.imageshow.ImageZoom;
72import com.android.gallery3d.filtershow.imageshow.MasterImage;
73import com.android.gallery3d.filtershow.presets.ImagePreset;
74import com.android.gallery3d.filtershow.provider.SharedImageProvider;
75import com.android.gallery3d.filtershow.tools.BitmapTask;
76import com.android.gallery3d.filtershow.tools.SaveCopyTask;
77import com.android.gallery3d.filtershow.ui.FilterIconButton;
78import com.android.gallery3d.filtershow.ui.FramedTextButton;
79import com.android.gallery3d.filtershow.ui.Spline;
80import com.android.gallery3d.util.GalleryUtils;
81import com.android.photos.data.GalleryBitmapPool;
82
83import java.io.File;
84import java.io.IOException;
85import java.lang.ref.WeakReference;
86import java.util.Vector;
87
88public class FilterShowActivity extends Activity implements OnItemClickListener,
89        OnShareTargetSelectedListener {
90
91    // fields for supporting crop action
92    public static final String CROP_ACTION = "com.android.camera.action.CROP";
93    private CropExtras mCropExtras = null;
94    private String mAction = "";
95    MasterImage mMasterImage = null;
96
97    public static final String TINY_PLANET_ACTION = "com.android.camera.action.TINY_PLANET";
98    public static final String LAUNCH_FULLSCREEN = "launch-fullscreen";
99    public static final int MAX_BMAP_IN_INTENT = 990000;
100    private final PanelController mPanelController = new PanelController();
101    private ImageLoader mImageLoader = null;
102    private ImageShow mImageShow = null;
103    private ImageTinyPlanet mImageTinyPlanet = null;
104
105    private View mSaveButton = null;
106
107    private EditorPlaceHolder mEditorPlaceHolder = new EditorPlaceHolder(this);
108
109    private static final int SELECT_PICTURE = 1;
110    private static final String LOGTAG = "FilterShowActivity";
111    protected static final boolean ANIMATE_PANELS = true;
112    private static int mImageBorderSize = 4; // in percent
113
114    private boolean mShowingTinyPlanet = false;
115    private boolean mShowingHistoryPanel = false;
116    private boolean mShowingImageStatePanel = false;
117
118    private final Vector<ImageShow> mImageViews = new Vector<ImageShow>();
119
120    private ShareActionProvider mShareActionProvider;
121    private File mSharedOutputFile = null;
122
123    private boolean mSharingImage = false;
124
125    private WeakReference<ProgressDialog> mSavingProgressDialog;
126
127    private LoadBitmapTask mLoadBitmapTask;
128    private FilterIconButton mNullFxFilter;
129    private FilterIconButton mNullBorderFilter;
130    private int mIconSeedSize = 140;
131
132
133    @Override
134    public void onCreate(Bundle savedInstanceState) {
135        super.onCreate(savedInstanceState);
136
137        clearGalleryBitmapPool();
138
139        setupMasterImage();
140        ImageFilterRS.createRenderscriptContext(this);
141        setDefaultValues();
142        fillEditors();
143
144        loadXML();
145        if (getResources().getConfiguration().orientation
146                == Configuration.ORIENTATION_LANDSCAPE) {
147            mShowingImageStatePanel = true;
148        }
149        if (mShowingHistoryPanel) {
150            findViewById(R.id.historyPanel).setVisibility(View.VISIBLE);
151        } else {
152            findViewById(R.id.historyPanel).setVisibility(View.GONE);
153        }
154        if (mShowingImageStatePanel) {
155            findViewById(R.id.imageStatePanel).setVisibility(View.VISIBLE);
156        } else {
157            findViewById(R.id.imageStatePanel).setVisibility(View.GONE);
158        }
159
160        setDefaultPreset();
161
162        processIntent();
163    }
164
165    private void loadXML() {
166        setContentView(R.layout.filtershow_activity);
167
168        ((ViewStub) findViewById(R.id.stateCategoryStub)).inflate();
169        ((ViewStub) findViewById(R.id.editorPanelStub)).inflate();
170        ((ViewStub) findViewById(R.id.historyPanelStub)).inflate();
171        ((ViewStub) findViewById(R.id.statePanelStub)).inflate();
172
173        ActionBar actionBar = getActionBar();
174        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
175        actionBar.setCustomView(R.layout.filtershow_actionbar);
176
177        mSaveButton = actionBar.getCustomView();
178        mSaveButton.setOnClickListener(new OnClickListener() {
179            @Override
180            public void onClick(View view) {
181                saveImage();
182            }
183        });
184
185        mImageShow = (ImageShow) findViewById(R.id.imageShow);
186        mImageTinyPlanet = (ImageTinyPlanet) findViewById(R.id.imageTinyPlanet);
187        mImageViews.add(mImageShow);
188        mImageViews.add(mImageTinyPlanet);
189
190        setupEditors();
191
192        mEditorPlaceHolder.hide();
193
194        mImageShow.setImageLoader(mImageLoader);
195        mImageTinyPlanet.setImageLoader(mImageLoader);
196
197        mPanelController.clear();
198        mPanelController.setActivity(this);
199        mPanelController.setEditorPlaceHolder(mEditorPlaceHolder);
200
201        mPanelController.addImageView(findViewById(R.id.imageShow));
202        mPanelController.addImageView(findViewById(R.id.imageTinyPlanet));
203
204        mPanelController.addPanel(R.id.fxButton, R.id.fxList, 0);
205        mPanelController.addPanel(R.id.borderButton, R.id.bordersList, 1);
206        mPanelController.addPanel(R.id.geometryButton, R.id.geometryList, 2);
207        mPanelController.addPanel(R.id.colorsButton, R.id.colorsFxList, 3);
208
209        fillFx((LinearLayout) findViewById(R.id.listFilters), R.id.fxButton);
210        setupBorders();
211        fillGeometry();
212        fillFilters();
213
214        mPanelController.addView(findViewById(R.id.applyEffect));
215
216        setupHistoryPanel();
217        setupStatePanel();
218    }
219
220    public void setupHistoryPanel() {
221        findViewById(R.id.resetOperationsButton).setOnClickListener(
222                createOnClickResetOperationsButton());
223        ListView operationsList = (ListView) findViewById(R.id.operationsList);
224        operationsList.setAdapter(mMasterImage.getHistory());
225        operationsList.setOnItemClickListener(this);
226    }
227
228    public void setupStatePanel() {
229        ListView imageStateList = (ListView) findViewById(R.id.imageStateList);
230        imageStateList.setAdapter(mMasterImage.getState());
231        mImageLoader.setAdapter(mMasterImage.getHistory());
232        mPanelController.setRowPanel(findViewById(R.id.secondRowPanel));
233        mPanelController.setUtilityPanel(this, findViewById(R.id.filterButtonsList));
234        mPanelController.setCurrentPanel(R.id.fxButton);
235    }
236
237    private void fillPanel(Vector<FilterRepresentation> representations, int layoutId, int buttonId) {
238        ImageButton button = (ImageButton) findViewById(buttonId);
239        LinearLayout layout = (LinearLayout) findViewById(layoutId);
240
241        for (FilterRepresentation representation : representations) {
242            setupFilterRepresentationButton(representation, layout, button);
243        }
244    }
245
246    private void fillFilters() {
247        Vector<FilterRepresentation> filtersRepresentations = new Vector<FilterRepresentation>();
248        FiltersManager filtersManager = FiltersManager.getManager();
249        filtersManager.addEffects(filtersRepresentations);
250        fillPanel(filtersRepresentations, R.id.listColorsFx, R.id.colorsButton);
251    }
252
253    private void fillGeometry() {
254        Vector<FilterRepresentation> filtersRepresentations = new Vector<FilterRepresentation>();
255        FiltersManager filtersManager = FiltersManager.getManager();
256
257        GeometryMetadata geo = new GeometryMetadata();
258        int[] editorsId = geo.getEditorIds();
259        for (int i = 0; i < editorsId.length; i++) {
260            int editorId = editorsId[i];
261            GeometryMetadata geometry = new GeometryMetadata(geo);
262            geometry.setEditorId(editorId);
263            EditorInfo editorInfo = (EditorInfo) mEditorPlaceHolder.getEditor(editorId);
264            geometry.setTextId(editorInfo.getTextId());
265            geometry.setOverlayId(editorInfo.getOverlayId());
266            geometry.setOverlayOnly(editorInfo.getOverlayOnly());
267            filtersRepresentations.add(geometry);
268        }
269
270        filtersManager.addTools(filtersRepresentations);
271        fillPanel(filtersRepresentations, R.id.listGeometry, R.id.geometryButton);
272    }
273
274    private void processIntent() {
275        Intent intent = getIntent();
276        if (intent.getBooleanExtra(LAUNCH_FULLSCREEN, false)) {
277            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
278        }
279
280        mAction = intent.getAction();
281
282        if (intent.getData() != null) {
283            startLoadBitmap(intent.getData());
284        } else {
285            pickImage();
286        }
287
288        // Handle behavior for various actions
289        if (mAction.equalsIgnoreCase(CROP_ACTION)) {
290            Bundle extras = intent.getExtras();
291            if (extras != null) {
292                mCropExtras = new CropExtras(extras.getInt(CropExtras.KEY_OUTPUT_X, 0),
293                        extras.getInt(CropExtras.KEY_OUTPUT_Y, 0),
294                        extras.getBoolean(CropExtras.KEY_SCALE, true) &&
295                                extras.getBoolean(CropExtras.KEY_SCALE_UP_IF_NEEDED, false),
296                        extras.getInt(CropExtras.KEY_ASPECT_X, 0),
297                        extras.getInt(CropExtras.KEY_ASPECT_Y, 0),
298                        extras.getBoolean(CropExtras.KEY_SET_AS_WALLPAPER, false),
299                        extras.getBoolean(CropExtras.KEY_RETURN_DATA, false),
300                        (Uri) extras.getParcelable(MediaStore.EXTRA_OUTPUT),
301                        extras.getString(CropExtras.KEY_OUTPUT_FORMAT),
302                        extras.getBoolean(CropExtras.KEY_SHOW_WHEN_LOCKED, false),
303                        extras.getFloat(CropExtras.KEY_SPOTLIGHT_X),
304                        extras.getFloat(CropExtras.KEY_SPOTLIGHT_Y));
305
306                if (mCropExtras.getShowWhenLocked()) {
307                    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
308                }
309                mImageShow.getImagePreset().mGeoData.setCropExtras(mCropExtras);
310
311                // FIXME: moving to editors breaks the crop action
312                EditorCrop crop = (EditorCrop) mEditorPlaceHolder.getEditor(EditorCrop.ID);
313
314                crop.setExtras(mCropExtras);
315                String s = getString(R.string.Fixed);
316                crop.setAspectString(s);
317                crop.setCropActionFlag(true);
318                mPanelController.setFixedAspect(mCropExtras.getAspectX() > 0
319                        && mCropExtras.getAspectY() > 0);
320            }
321        }
322    }
323
324    private void setupEditors() {
325        mEditorPlaceHolder.setContainer((FrameLayout) findViewById(R.id.editorContainer));
326        EditorManager.addEditors(mEditorPlaceHolder);
327        mEditorPlaceHolder.setOldViews(mImageViews);
328        mEditorPlaceHolder.setImageLoader(mImageLoader);
329    }
330
331    private void fillEditors() {
332        mEditorPlaceHolder.addEditor(new EditorDraw());
333        mEditorPlaceHolder.addEditor(new BasicEditor());
334        mEditorPlaceHolder.addEditor(new ImageOnlyEditor());
335        mEditorPlaceHolder.addEditor(new EditorTinyPlanet());
336        mEditorPlaceHolder.addEditor(new EditorRedEye());
337        mEditorPlaceHolder.addEditor(new EditorCrop());
338        mEditorPlaceHolder.addEditor(new EditorFlip());
339        mEditorPlaceHolder.addEditor(new EditorRotate());
340        mEditorPlaceHolder.addEditor(new EditorStraighten());
341    }
342
343    private void setDefaultValues() {
344        ImageFilter.setActivityForMemoryToasts(this);
345
346        Resources res = getResources();
347        // TODO: add a mechanism to set the resources in FiltersManagmer
348        ImageFilterBorder filterBorder = (ImageFilterBorder) FiltersManager.getManager().getFilter(ImageFilterBorder.class);
349        filterBorder.setResources(res);
350        filterBorder = (ImageFilterBorder) FiltersManager.getPreviewManager().getFilter(ImageFilterBorder.class);
351        filterBorder.setResources(res);
352        ImageFilterFx filterFx = (ImageFilterFx) FiltersManager.getManager().getFilter(ImageFilterFx.class);
353        filterFx.setResources(res);
354        filterFx = (ImageFilterFx) FiltersManager.getPreviewManager().getFilter(ImageFilterFx.class);
355        filterFx.setResources(res);
356
357        ImageShow.setDefaultBackgroundColor(res.getColor(R.color.background_screen));
358        // TODO: get those values from XML.
359        ImageZoom.setZoomedSize(getPixelsFromDip(256));
360        FramedTextButton.setTextSize((int) getPixelsFromDip(14));
361        FramedTextButton.setTrianglePadding((int) getPixelsFromDip(4));
362        FramedTextButton.setTriangleSize((int) getPixelsFromDip(10));
363        ImageShow.setTextSize((int) getPixelsFromDip(12));
364        ImageShow.setTextPadding((int) getPixelsFromDip(10));
365        ImageShow.setOriginalTextMargin((int) getPixelsFromDip(4));
366        ImageShow.setOriginalTextSize((int) getPixelsFromDip(18));
367        ImageShow.setOriginalText(res.getString(R.string.original_picture_text));
368        mIconSeedSize = res.getDimensionPixelSize(R.dimen.thumbnail_size);
369        // TODO: pick correct value
370        // MasterImage.setIconSeedSize(mIconSeedSize);
371
372        Drawable curveHandle = res.getDrawable(R.drawable.camera_crop);
373        int curveHandleSize = (int) res.getDimension(R.dimen.crop_indicator_size);
374        Spline.setCurveHandle(curveHandle, curveHandleSize);
375        Spline.setCurveWidth((int) getPixelsFromDip(3));
376
377        ImageCrop.setAspectTextSize((int) getPixelsFromDip(18));
378        ImageCrop.setTouchTolerance((int) getPixelsFromDip(25));
379        ImageCrop.setMinCropSize((int) getPixelsFromDip(55));
380    }
381
382    private void startLoadBitmap(Uri uri) {
383        final View filters = findViewById(R.id.filtersPanel);
384        final View loading = findViewById(R.id.loading);
385        final View imageShow = findViewById(R.id.imageShow);
386        imageShow.setVisibility(View.INVISIBLE);
387        filters.setVisibility(View.INVISIBLE);
388        loading.setVisibility(View.VISIBLE);
389
390        View tinyPlanetView = findViewById(EditorTinyPlanet.ID);
391        if (tinyPlanetView != null) {
392            mShowingTinyPlanet = false;
393            tinyPlanetView.setVisibility(View.GONE);
394        }
395        mLoadBitmapTask = new LoadBitmapTask(tinyPlanetView);
396        mLoadBitmapTask.execute(uri);
397    }
398
399    private void setupBorders() {
400        LinearLayout list = (LinearLayout) findViewById(R.id.listBorders);
401        Vector<FilterRepresentation> borders = new Vector<FilterRepresentation>();
402        borders.add(new FilterImageBorderRepresentation(0));
403        borders.add(new FilterImageBorderRepresentation(R.drawable.filtershow_border_4x5));
404        borders.add(new FilterImageBorderRepresentation(R.drawable.filtershow_border_brush));
405        borders.add(new FilterImageBorderRepresentation(R.drawable.filtershow_border_grunge));
406        borders.add(new FilterImageBorderRepresentation(R.drawable.filtershow_border_sumi_e));
407        borders.add(new FilterImageBorderRepresentation(R.drawable.filtershow_border_tape));
408        borders.add(new FilterColorBorderRepresentation(Color.BLACK, mImageBorderSize, 0));
409        borders.add(new FilterColorBorderRepresentation(Color.BLACK, mImageBorderSize,
410                mImageBorderSize));
411        borders.add(new FilterColorBorderRepresentation(Color.WHITE, mImageBorderSize, 0));
412        borders.add(new FilterColorBorderRepresentation(Color.WHITE, mImageBorderSize,
413                mImageBorderSize));
414        int creamColor = Color.argb(255, 237, 237, 227);
415        borders.add(new FilterColorBorderRepresentation(creamColor, mImageBorderSize, 0));
416        borders.add(new FilterColorBorderRepresentation(creamColor, mImageBorderSize,
417                mImageBorderSize));
418        for (int i = 0; i < borders.size(); i++) {
419            FilterRepresentation filter = borders.elementAt(i);
420            filter.setName(getString(R.string.borders));
421            if (i == 0) {
422                filter.setName(getString(R.string.none));
423            }
424            ImageButton borderButton = (ImageButton) findViewById(R.id.borderButton);
425            FilterIconButton b = setupFilterRepresentationButton(filter, list, borderButton);
426            if (i == 0) {
427                mNullBorderFilter = b;
428                mNullBorderFilter.setSelected(true);
429            }
430        }
431    }
432
433    private class LoadBitmapTask extends AsyncTask<Uri, Boolean, Boolean> {
434        View mTinyPlanetButton;
435        int mBitmapSize;
436
437        public LoadBitmapTask(View button) {
438            mTinyPlanetButton = button;
439            mBitmapSize = getScreenImageSize();
440        }
441
442        @Override
443        protected Boolean doInBackground(Uri... params) {
444            if (!mImageLoader.loadBitmap(params[0], mBitmapSize)) {
445                return false;
446            }
447            publishProgress(mImageLoader.queryLightCycle360());
448            return true;
449        }
450
451        @Override
452        protected void onProgressUpdate(Boolean... values) {
453            super.onProgressUpdate(values);
454            if (isCancelled()) {
455                return;
456            }
457            if (values[0]) {
458                mShowingTinyPlanet = true;
459                mTinyPlanetButton.setVisibility(View.VISIBLE);
460            }
461        }
462
463        @Override
464        protected void onPostExecute(Boolean result) {
465
466            if (isCancelled()) {
467                return;
468            }
469
470            if (!result) {
471                cannotLoadImage();
472            }
473
474            final View loading = findViewById(R.id.loading);
475            loading.setVisibility(View.GONE);
476            final View filters = findViewById(R.id.filtersPanel);
477            filters.setVisibility(View.VISIBLE);
478            if (PanelController.useAnimationsLayer()) {
479                float y = filters.getY();
480                filters.setY(y + filters.getHeight());
481                filters.animate().setDuration(600).y(y).withLayer().start();
482            }
483            final View imageShow = findViewById(R.id.imageShow);
484            imageShow.setVisibility(View.VISIBLE);
485
486            Bitmap largeBitmap = mImageLoader.getOriginalBitmapLarge();
487            FilteringPipeline pipeline = FilteringPipeline.getPipeline();
488            pipeline.setOriginal(largeBitmap);
489            float previewScale = (float) largeBitmap.getWidth() / (float) mImageLoader.getOriginalBounds().width();
490            pipeline.setPreviewScaleFactor(previewScale);
491
492            MasterImage.getImage().setOriginalGeometry(largeBitmap);
493            mLoadBitmapTask = null;
494
495            if (mAction == CROP_ACTION) {
496                mPanelController.showComponent(findViewById(EditorCrop.ID));
497            } else if (mAction == TINY_PLANET_ACTION) {
498                mPanelController.showComponent(findViewById(EditorTinyPlanet.ID));
499            }
500            pipeline.turnOnPipeline(true);
501            super.onPostExecute(result);
502        }
503
504    }
505
506    private void clearGalleryBitmapPool() {
507        (new AsyncTask<Void, Void, Void>() {
508            @Override
509            protected Void doInBackground(Void... params) {
510                // Free memory held in Gallery's Bitmap pool.  May be O(n) for n bitmaps.
511                GalleryBitmapPool.getInstance().clear();
512                return null;
513            }
514        }).execute();
515    }
516
517    @Override
518    protected void onDestroy() {
519        if (mLoadBitmapTask != null) {
520            mLoadBitmapTask.cancel(false);
521        }
522        // TODO:  Using singletons is a bad design choice for many of these
523        // due static reference leaks and in general.  Please refactor.
524        MasterImage.reset();
525        ImageFilterRS.destroyRenderScriptContext();
526        FilteringPipeline.reset();
527        ImageFilter.resetStatics();
528        FiltersManager.getPreviewManager().freeRSFilterScripts();
529        FiltersManager.getManager().freeRSFilterScripts();
530        FiltersManager.reset();
531        super.onDestroy();
532    }
533
534    private int translateMainPanel(View viewPanel) {
535        int accessoryPanelWidth = viewPanel.getWidth();
536        int mainViewWidth = findViewById(R.id.mainView).getWidth();
537        int mainPanelWidth = mImageShow.getDisplayedImageBounds().width();
538        if (mainPanelWidth == 0) {
539            mainPanelWidth = mainViewWidth;
540        }
541        int filtersPanelWidth = findViewById(R.id.filtersPanel).getWidth();
542        if (mainPanelWidth < filtersPanelWidth) {
543            mainPanelWidth = filtersPanelWidth;
544        }
545        int leftOver = mainViewWidth - mainPanelWidth - accessoryPanelWidth;
546        if (leftOver < 0) {
547            return -accessoryPanelWidth;
548        }
549        return 0;
550    }
551
552    private int getScreenImageSize() {
553        DisplayMetrics metrics = new DisplayMetrics();
554        Display display = getWindowManager().getDefaultDisplay();
555        Point size = new Point();
556        display.getSize(size);
557        display.getMetrics(metrics);
558        int msize = Math.min(size.x, size.y);
559        return (133 * msize) / metrics.densityDpi;
560    }
561
562    private void showSavingProgress(String albumName) {
563        ProgressDialog progress;
564        if (mSavingProgressDialog != null) {
565            progress = mSavingProgressDialog.get();
566            if (progress != null) {
567                progress.show();
568                return;
569            }
570        }
571        // TODO: Allow cancellation of the saving process
572        String progressText;
573        if (albumName == null) {
574            progressText = getString(R.string.saving_image);
575        } else {
576            progressText = getString(R.string.filtershow_saving_image, albumName);
577        }
578        progress = ProgressDialog.show(this, "", progressText, true, false);
579        mSavingProgressDialog = new WeakReference<ProgressDialog>(progress);
580    }
581
582    private void hideSavingProgress() {
583        if (mSavingProgressDialog != null) {
584            ProgressDialog progress = mSavingProgressDialog.get();
585            if (progress != null)
586                progress.dismiss();
587        }
588    }
589
590    public void completeSaveImage(Uri saveUri) {
591        if (mSharingImage && mSharedOutputFile != null) {
592            // Image saved, we unblock the content provider
593            Uri uri = Uri.withAppendedPath(SharedImageProvider.CONTENT_URI,
594                    Uri.encode(mSharedOutputFile.getAbsolutePath()));
595            ContentValues values = new ContentValues();
596            values.put(SharedImageProvider.PREPARE, false);
597            getContentResolver().insert(uri, values);
598        }
599        setResult(RESULT_OK, new Intent().setData(saveUri));
600        hideSavingProgress();
601        finish();
602    }
603
604    @Override
605    public boolean onShareTargetSelected(ShareActionProvider arg0, Intent arg1) {
606        // First, let's tell the SharedImageProvider that it will need to wait
607        // for the image
608        Uri uri = Uri.withAppendedPath(SharedImageProvider.CONTENT_URI,
609                Uri.encode(mSharedOutputFile.getAbsolutePath()));
610        ContentValues values = new ContentValues();
611        values.put(SharedImageProvider.PREPARE, true);
612        getContentResolver().insert(uri, values);
613        mSharingImage = true;
614
615        // Process and save the image in the background.
616        showSavingProgress(null);
617        mImageShow.saveImage(this, mSharedOutputFile);
618        return true;
619    }
620
621    private Intent getDefaultShareIntent() {
622        Intent intent = new Intent(Intent.ACTION_SEND);
623        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
624        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
625        intent.setType(SharedImageProvider.MIME_TYPE);
626        mSharedOutputFile = SaveCopyTask.getNewFile(this, mImageLoader.getUri());
627        Uri uri = Uri.withAppendedPath(SharedImageProvider.CONTENT_URI,
628                Uri.encode(mSharedOutputFile.getAbsolutePath()));
629        intent.putExtra(Intent.EXTRA_STREAM, uri);
630        return intent;
631    }
632
633    @Override
634    public boolean onCreateOptionsMenu(Menu menu) {
635        getMenuInflater().inflate(R.menu.filtershow_activity_menu, menu);
636        MenuItem showHistory = menu.findItem(R.id.operationsButton);
637        if (mShowingHistoryPanel) {
638            showHistory.setTitle(R.string.hide_history_panel);
639        } else {
640            showHistory.setTitle(R.string.show_history_panel);
641        }
642        MenuItem showState = menu.findItem(R.id.showImageStateButton);
643        if (mShowingImageStatePanel) {
644            showState.setTitle(R.string.hide_imagestate_panel);
645        } else {
646            showState.setTitle(R.string.show_imagestate_panel);
647        }
648        mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.menu_share)
649                .getActionProvider();
650        mShareActionProvider.setShareIntent(getDefaultShareIntent());
651        mShareActionProvider.setOnShareTargetSelectedListener(this);
652
653        MenuItem undoItem = menu.findItem(R.id.undoButton);
654        MenuItem redoItem = menu.findItem(R.id.redoButton);
655        MenuItem resetItem = menu.findItem(R.id.resetHistoryButton);
656        mMasterImage.getHistory().setMenuItems(undoItem, redoItem, resetItem);
657        return true;
658    }
659
660    @Override
661    public void onPause() {
662        super.onPause();
663        if (mShareActionProvider != null) {
664            mShareActionProvider.setOnShareTargetSelectedListener(null);
665        }
666    }
667
668    @Override
669    public void onResume() {
670        super.onResume();
671        if (mShareActionProvider != null) {
672            mShareActionProvider.setOnShareTargetSelectedListener(this);
673        }
674    }
675
676    @Override
677    public boolean onOptionsItemSelected(MenuItem item) {
678        switch (item.getItemId()) {
679            case R.id.undoButton: {
680                mPanelController.resetParameters();
681                HistoryAdapter adapter = mMasterImage.getHistory();
682                int position = adapter.undo();
683                mMasterImage.onHistoryItemClick(position);
684                mImageShow.showToast("Undo");
685                invalidateViews();
686                return true;
687            }
688            case R.id.redoButton: {
689                HistoryAdapter adapter = mMasterImage.getHistory();
690                int position = adapter.redo();
691                mMasterImage.onHistoryItemClick(position);
692                mImageShow.showToast("Redo");
693                invalidateViews();
694                return true;
695            }
696            case R.id.resetHistoryButton: {
697                resetHistory();
698                return true;
699            }
700            case R.id.showImageStateButton: {
701                toggleImageStatePanel();
702                return true;
703            }
704            case R.id.operationsButton: {
705                toggleHistoryPanel();
706                return true;
707            }
708            case android.R.id.home: {
709                saveImage();
710                return true;
711            }
712        }
713        return false;
714    }
715
716    public void enableSave(boolean enable) {
717        if (mSaveButton != null)
718            mSaveButton.setEnabled(enable);
719    }
720
721    public FilterIconButton setupFilterRepresentationButton(FilterRepresentation representation, LinearLayout panel, View button) {
722        LayoutInflater inflater =
723                (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
724        FilterIconButton icon = (FilterIconButton) inflater.inflate(R.layout.filtericonbutton,
725                panel, false);
726        if (representation.getTextId() != 0) {
727            representation.setName(getString(representation.getTextId()));
728        }
729        String text = representation.getName();
730        icon.setup(text, mPanelController, panel);
731        icon.setFilterRepresentation(representation);
732        icon.setId(representation.getEditorId());
733        mPanelController.addComponent(button, icon);
734        panel.addView(icon);
735        return icon;
736    }
737
738    private void fillFx(LinearLayout listFilters, int buttonId) {
739        // TODO: use listview
740        // TODO: load the filters straight from the filesystem
741
742        FilterFxRepresentation[] fxArray = new FilterFxRepresentation[18];
743        int p = 0;
744
745        int[] drawid = {
746                R.drawable.filtershow_fx_0005_punch,
747                R.drawable.filtershow_fx_0000_vintage,
748                R.drawable.filtershow_fx_0004_bw_contrast,
749                R.drawable.filtershow_fx_0002_bleach,
750                R.drawable.filtershow_fx_0001_instant,
751                R.drawable.filtershow_fx_0007_washout,
752                R.drawable.filtershow_fx_0003_blue_crush,
753                R.drawable.filtershow_fx_0008_washout_color,
754                R.drawable.filtershow_fx_0006_x_process
755        };
756
757        int[] fxNameid = {
758                R.string.ffx_punch,
759                R.string.ffx_vintage,
760                R.string.ffx_bw_contrast,
761                R.string.ffx_bleach,
762                R.string.ffx_instant,
763                R.string.ffx_washout,
764                R.string.ffx_blue_crush,
765                R.string.ffx_washout_color,
766                R.string.ffx_x_process
767        };
768
769        for (int i = 0; i < drawid.length; i++) {
770            FilterFxRepresentation fx = new FilterFxRepresentation(getString(fxNameid[i]), drawid[i], fxNameid[i]);
771            fxArray[p++] = fx;
772        }
773
774        ImageButton button = (ImageButton) findViewById(buttonId);
775
776        FilterFxRepresentation nullFx = new FilterFxRepresentation(getString(R.string.none), 0, R.string.none);
777        mNullFxFilter = setupFilterRepresentationButton(nullFx, listFilters, button);
778        mNullFxFilter.setSelected(true);
779
780        Vector<FilterRepresentation> filtersRepresentations = new Vector<FilterRepresentation>();
781        FiltersManager.getManager().addLooks(filtersRepresentations);
782        for (FilterRepresentation representation : filtersRepresentations) {
783            setupFilterRepresentationButton(representation, listFilters, button);
784        }
785
786        for (int i = 0; i < p; i++) {
787            setupFilterRepresentationButton(fxArray[i], listFilters, button);
788        }
789    }
790
791    public void setDefaultPreset() {
792        // Default preset (original)
793        ImagePreset preset = new ImagePreset(getString(R.string.history_original)); // empty
794        preset.setImageLoader(mImageLoader);
795
796        mMasterImage.setPreset(preset, true);
797    }
798
799    // //////////////////////////////////////////////////////////////////////////////
800    // Some utility functions
801    // TODO: finish the cleanup.
802
803    public void invalidateViews() {
804        for (ImageShow views : mImageViews) {
805            views.invalidate();
806            views.updateImage();
807        }
808    }
809
810    public void hideImageViews() {
811        for (View view : mImageViews) {
812            view.setVisibility(View.GONE);
813        }
814        mEditorPlaceHolder.hide();
815    }
816
817    // //////////////////////////////////////////////////////////////////////////////
818    // imageState panel...
819
820    public boolean isShowingHistoryPanel() {
821        return mShowingHistoryPanel;
822    }
823
824    private void toggleImageStatePanel() {
825        final View viewList = findViewById(R.id.imageStatePanel);
826
827        if (mShowingHistoryPanel) {
828            findViewById(R.id.historyPanel).setVisibility(View.GONE);
829            mShowingHistoryPanel = false;
830        }
831
832        if (!mShowingImageStatePanel) {
833            mShowingImageStatePanel = true;
834            viewList.setVisibility(View.VISIBLE);
835        } else {
836            mShowingImageStatePanel = false;
837            viewList.setVisibility(View.GONE);
838        }
839        invalidateOptionsMenu();
840    }
841
842    @Override
843    public void onConfigurationChanged(Configuration newConfig)
844    {
845        super.onConfigurationChanged(newConfig);
846        setDefaultValues();
847        loadXML();
848        if (getResources().getConfiguration().orientation
849                == Configuration.ORIENTATION_LANDSCAPE) {
850            mShowingImageStatePanel = true;
851        } else if (mShowingImageStatePanel) {
852            toggleImageStatePanel();
853        }
854        if (mShowingHistoryPanel) {
855            toggleHistoryPanel();
856        }
857        if (mShowingTinyPlanet == false) {
858            View tinyPlanetView = findViewById(EditorTinyPlanet.ID);
859            if (tinyPlanetView != null) {
860                tinyPlanetView.setVisibility(View.GONE);
861            }
862        }
863        final View loading = findViewById(R.id.loading);
864        loading.setVisibility(View.GONE);
865    }
866
867    public void setupMasterImage() {
868        mImageLoader = new ImageLoader(this, getApplicationContext());
869
870        HistoryAdapter mHistoryAdapter = new HistoryAdapter(
871                this, R.layout.filtershow_history_operation_row,
872                R.id.rowTextView);
873        ImageStateAdapter mImageStateAdapter = new ImageStateAdapter(this,
874                R.layout.filtershow_imagestate_row);
875
876        MasterImage.reset();
877        mMasterImage = MasterImage.getImage();
878        mMasterImage.setHistoryAdapter(mHistoryAdapter);
879        mMasterImage.setStateAdapter(mImageStateAdapter);
880        mMasterImage.setActivity(this);
881        mMasterImage.setImageLoader(mImageLoader);
882    }
883
884    // //////////////////////////////////////////////////////////////////////////////
885    // history panel...
886
887    public void toggleHistoryPanel() {
888        final View view = findViewById(R.id.mainPanel);
889        final View viewList = findViewById(R.id.historyPanel);
890
891        if (mShowingImageStatePanel) {
892            findViewById(R.id.imageStatePanel).setVisibility(View.GONE);
893        }
894
895        int translate = translateMainPanel(viewList);
896        if (!mShowingHistoryPanel) {
897            mShowingHistoryPanel = true;
898            if (getResources().getConfiguration().orientation
899                    == Configuration.ORIENTATION_PORTRAIT) {
900                // If portrait, always remove the state panel
901                mShowingImageStatePanel = false;
902                if (PanelController.useAnimationsLayer()) {
903                    view.animate().setDuration(200).x(translate)
904                            .withLayer().withEndAction(new Runnable() {
905                        @Override
906                        public void run() {
907                            viewList.setAlpha(0);
908                            viewList.setVisibility(View.VISIBLE);
909                            viewList.animate().setDuration(100)
910                                    .alpha(1.0f).start();
911                        }
912                    }).start();
913                } else {
914                    view.setX(translate);
915                    viewList.setAlpha(0);
916                    viewList.setVisibility(View.VISIBLE);
917                    viewList.animate().setDuration(100)
918                            .alpha(1.0f).start();
919                }
920            } else {
921                findViewById(R.id.filtersPanel).setVisibility(View.GONE);
922                viewList.setVisibility(View.VISIBLE);
923            }
924        } else {
925            mShowingHistoryPanel = false;
926            if (getResources().getConfiguration().orientation
927                    == Configuration.ORIENTATION_PORTRAIT) {
928                viewList.setVisibility(View.INVISIBLE);
929                if (PanelController.useAnimationsLayer()) {
930                    view.animate().setDuration(200).x(0).withLayer()
931                            .start();
932                } else {
933                    view.setX(0);
934                }
935            } else {
936                viewList.setVisibility(View.GONE);
937                findViewById(R.id.filtersPanel).setVisibility(View.VISIBLE);
938                // In landscape, bring back the state panel if it was there
939                if (mShowingImageStatePanel) {
940                    findViewById(R.id.imageStatePanel).setVisibility(View.VISIBLE);
941                }
942            }
943        }
944        invalidateOptionsMenu();
945    }
946
947    public void dispatchNullFilterClick() {
948        mNullFxFilter.onClick(mNullFxFilter);
949        mNullBorderFilter.onClick(mNullBorderFilter);
950    }
951
952    void resetHistory() {
953        dispatchNullFilterClick();
954        HistoryAdapter adapter = mMasterImage.getHistory();
955        adapter.reset();
956        ImagePreset original = new ImagePreset(adapter.getItem(0));
957        mMasterImage.setPreset(original, true);
958        mPanelController.resetParameters();
959        invalidateViews();
960    }
961
962    // reset button in the history panel.
963    private OnClickListener createOnClickResetOperationsButton() {
964        return new View.OnClickListener() {
965            @Override
966            public void onClick(View v) {
967                resetHistory();
968            }
969        };
970    }
971
972    @Override
973    public void onBackPressed() {
974        if (mPanelController.onBackPressed()) {
975            saveImage();
976        }
977    }
978
979    public PanelController getPanelController() {
980        return mPanelController;
981    }
982
983    public void cannotLoadImage() {
984        CharSequence text = getString(R.string.cannot_load_image);
985        Toast toast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
986        toast.show();
987        finish();
988    }
989
990    // //////////////////////////////////////////////////////////////////////////////
991
992    public float getPixelsFromDip(float value) {
993        Resources r = getResources();
994        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value,
995                r.getDisplayMetrics());
996    }
997
998    @Override
999    public void onItemClick(AdapterView<?> parent, View view, int position,
1000            long id) {
1001        mMasterImage.onHistoryItemClick(position);
1002        invalidateViews();
1003    }
1004
1005    public void pickImage() {
1006        Intent intent = new Intent();
1007        intent.setType("image/*");
1008        intent.setAction(Intent.ACTION_GET_CONTENT);
1009        startActivityForResult(Intent.createChooser(intent, getString(R.string.select_image)),
1010                SELECT_PICTURE);
1011    }
1012
1013    @Override
1014    public void onActivityResult(int requestCode, int resultCode, Intent data) {
1015        if (resultCode == RESULT_OK) {
1016            if (requestCode == SELECT_PICTURE) {
1017                Uri selectedImageUri = data.getData();
1018                startLoadBitmap(selectedImageUri);
1019            }
1020        }
1021    }
1022
1023    private boolean mSaveToExtraUri = false;
1024    private boolean mSaveAsWallpaper = false;
1025    private boolean mReturnAsExtra = false;
1026    private boolean mOutputted = false;
1027
1028    public void saveImage() {
1029        if (mCropExtras != null) {
1030            if (mCropExtras.getExtraOutput() != null) {
1031                mSaveToExtraUri = true;
1032                mOutputted = true;
1033            }
1034            if (mCropExtras.getSetAsWallpaper()) {
1035                mSaveAsWallpaper = true;
1036                mOutputted = true;
1037            }
1038            if (mCropExtras.getReturnData()) {
1039
1040                mReturnAsExtra = true;
1041                mOutputted = true;
1042            }
1043
1044            if (mOutputted) {
1045                mImageShow.getImagePreset().mGeoData.setUseCropExtrasFlag(true);
1046                showSavingProgress(null);
1047                mImageShow.returnFilteredResult(this);
1048            }
1049        }
1050        if (!mOutputted) {
1051            if (mImageShow.hasModifications()) {
1052                // Get the name of the album, to which the image will be saved
1053                File saveDir = SaveCopyTask.getFinalSaveDirectory(this, mImageLoader.getUri());
1054                int bucketId = GalleryUtils.getBucketId(saveDir.getPath());
1055                String albumName = LocalAlbum.getLocalizedName(getResources(), bucketId, null);
1056                showSavingProgress(albumName);
1057                mImageShow.saveImage(this, null);
1058            } else {
1059                done();
1060            }
1061        }
1062    }
1063
1064    public void onFilteredResult(Bitmap filtered) {
1065        Intent intent = new Intent();
1066        intent.putExtra(CropExtras.KEY_CROPPED_RECT, mImageShow.getImageCropBounds());
1067        if (mSaveToExtraUri) {
1068            mImageShow.saveToUri(filtered, mCropExtras.getExtraOutput(),
1069                    mCropExtras.getOutputFormat(), this);
1070        }
1071        if (mSaveAsWallpaper) {
1072            setWallpaperInBackground(filtered);
1073        }
1074        if (mReturnAsExtra) {
1075            if (filtered != null) {
1076                int bmapSize = filtered.getRowBytes() * filtered.getHeight();
1077                /*
1078                 * Max size of Binder transaction buffer is 1Mb, so constrain
1079                 * Bitmap to be somewhat less than this, otherwise we get
1080                 * TransactionTooLargeExceptions.
1081                 */
1082                if (bmapSize > MAX_BMAP_IN_INTENT) {
1083                    Log.w(LOGTAG, "Bitmap too large to be returned via intent");
1084                } else {
1085                    intent.putExtra(CropExtras.KEY_DATA, filtered);
1086                }
1087            }
1088        }
1089        setResult(RESULT_OK, intent);
1090        if (!mSaveToExtraUri) {
1091            done();
1092        }
1093    }
1094
1095    void setWallpaperInBackground(final Bitmap bmap) {
1096        Toast.makeText(this, R.string.setting_wallpaper, Toast.LENGTH_LONG).show();
1097        BitmapTask.Callbacks<FilterShowActivity> cb = new BitmapTask.Callbacks<FilterShowActivity>() {
1098            @Override
1099            public void onComplete(Bitmap result) {}
1100
1101            @Override
1102            public void onCancel() {}
1103
1104            @Override
1105            public Bitmap onExecute(FilterShowActivity param) {
1106                try {
1107                    WallpaperManager.getInstance(param).setBitmap(bmap);
1108                } catch (IOException e) {
1109                    Log.w(LOGTAG, "fail to set wall paper", e);
1110                }
1111                return null;
1112            }
1113        };
1114        (new BitmapTask<FilterShowActivity>(cb)).execute(this);
1115    }
1116
1117    public void done() {
1118        if (mOutputted) {
1119            hideSavingProgress();
1120        }
1121        finish();
1122    }
1123
1124    static {
1125        System.loadLibrary("jni_filtershow_filters");
1126    }
1127
1128}
1129