FilterShowActivity.java revision f7f24e806ef4646db3f49f637e86417d3a0bebf2
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.AlertDialog;
21import android.app.ProgressDialog;
22import android.content.ComponentName;
23import android.content.ContentValues;
24import android.content.Context;
25import android.content.DialogInterface;
26import android.content.Intent;
27import android.content.ServiceConnection;
28import android.content.pm.ActivityInfo;
29import android.content.res.Configuration;
30import android.content.res.Resources;
31import android.graphics.Bitmap;
32import android.graphics.Color;
33import android.graphics.Matrix;
34import android.graphics.Point;
35import android.graphics.Rect;
36import android.graphics.RectF;
37import android.graphics.drawable.ColorDrawable;
38import android.graphics.drawable.Drawable;
39import android.net.Uri;
40import android.os.AsyncTask;
41import android.os.Bundle;
42import android.os.CancellationSignal;
43import android.os.Handler;
44import android.os.IBinder;
45import android.support.v4.app.DialogFragment;
46import android.support.v4.app.Fragment;
47import android.support.v4.app.FragmentActivity;
48import android.support.v4.app.FragmentTransaction;
49import android.util.DisplayMetrics;
50import android.util.Log;
51import android.util.TypedValue;
52import android.view.Menu;
53import android.view.MenuItem;
54import android.view.MotionEvent;
55import android.view.View;
56import android.view.View.OnClickListener;
57import android.view.ViewPropertyAnimator;
58import android.view.WindowManager;
59import android.widget.AdapterView;
60import android.widget.AdapterView.OnItemClickListener;
61import android.widget.FrameLayout;
62import android.widget.ShareActionProvider;
63import android.widget.ShareActionProvider.OnShareTargetSelectedListener;
64import android.widget.Spinner;
65import android.widget.Toast;
66
67import com.android.gallery3d.R;
68import com.android.gallery3d.app.PhotoPage;
69import com.android.gallery3d.data.LocalAlbum;
70import com.android.gallery3d.filtershow.cache.ImageLoader;
71import com.android.gallery3d.filtershow.category.Action;
72import com.android.gallery3d.filtershow.category.CategoryAdapter;
73import com.android.gallery3d.filtershow.category.CategorySelected;
74import com.android.gallery3d.filtershow.category.CategoryView;
75import com.android.gallery3d.filtershow.category.MainPanel;
76import com.android.gallery3d.filtershow.category.SwipableView;
77import com.android.gallery3d.filtershow.data.UserPresetsManager;
78import com.android.gallery3d.filtershow.editors.BasicEditor;
79import com.android.gallery3d.filtershow.editors.Editor;
80import com.android.gallery3d.filtershow.editors.EditorChanSat;
81import com.android.gallery3d.filtershow.editors.EditorColorBorder;
82import com.android.gallery3d.filtershow.editors.EditorCrop;
83import com.android.gallery3d.filtershow.editors.EditorDraw;
84import com.android.gallery3d.filtershow.editors.EditorGrad;
85import com.android.gallery3d.filtershow.editors.EditorManager;
86import com.android.gallery3d.filtershow.editors.EditorMirror;
87import com.android.gallery3d.filtershow.editors.EditorPanel;
88import com.android.gallery3d.filtershow.editors.EditorRedEye;
89import com.android.gallery3d.filtershow.editors.EditorRotate;
90import com.android.gallery3d.filtershow.editors.EditorStraighten;
91import com.android.gallery3d.filtershow.editors.EditorTinyPlanet;
92import com.android.gallery3d.filtershow.editors.ImageOnlyEditor;
93import com.android.gallery3d.filtershow.filters.FilterDrawRepresentation;
94import com.android.gallery3d.filtershow.filters.FilterMirrorRepresentation;
95import com.android.gallery3d.filtershow.filters.FilterRepresentation;
96import com.android.gallery3d.filtershow.filters.FilterRotateRepresentation;
97import com.android.gallery3d.filtershow.filters.FilterUserPresetRepresentation;
98import com.android.gallery3d.filtershow.filters.FiltersManager;
99import com.android.gallery3d.filtershow.filters.ImageFilter;
100import com.android.gallery3d.filtershow.history.HistoryItem;
101import com.android.gallery3d.filtershow.history.HistoryManager;
102import com.android.gallery3d.filtershow.imageshow.ImageShow;
103import com.android.gallery3d.filtershow.imageshow.MasterImage;
104import com.android.gallery3d.filtershow.imageshow.Spline;
105import com.android.gallery3d.filtershow.info.InfoPanel;
106import com.android.gallery3d.filtershow.pipeline.CachingPipeline;
107import com.android.gallery3d.filtershow.pipeline.ImagePreset;
108import com.android.gallery3d.filtershow.pipeline.ProcessingService;
109import com.android.gallery3d.filtershow.presets.PresetManagementDialog;
110import com.android.gallery3d.filtershow.presets.UserPresetsAdapter;
111import com.android.gallery3d.filtershow.provider.SharedImageProvider;
112import com.android.gallery3d.filtershow.state.StateAdapter;
113import com.android.gallery3d.filtershow.tools.SaveImage;
114import com.android.gallery3d.filtershow.tools.XmpPresets;
115import com.android.gallery3d.filtershow.tools.XmpPresets.XMresults;
116import com.android.gallery3d.filtershow.ui.ExportDialog;
117import com.android.gallery3d.filtershow.ui.FramedTextButton;
118import com.android.gallery3d.util.GalleryUtils;
119import com.android.gallery3d.util.PrintJob;
120import com.android.gallery3d.util.UsageStatistics;
121import com.android.photos.data.GalleryBitmapPool;
122
123import java.io.File;
124import java.io.FileDescriptor;
125import java.io.FileOutputStream;
126import java.lang.ref.WeakReference;
127import java.util.ArrayList;
128import java.util.Vector;
129
130public class FilterShowActivity extends FragmentActivity implements OnItemClickListener,
131        OnShareTargetSelectedListener, DialogInterface.OnShowListener,
132        DialogInterface.OnDismissListener{
133
134    private String mAction = "";
135    MasterImage mMasterImage = null;
136
137    private static final long LIMIT_SUPPORTS_HIGHRES = 134217728; // 128Mb
138
139    public static final String TINY_PLANET_ACTION = "com.android.camera.action.TINY_PLANET";
140    public static final String LAUNCH_FULLSCREEN = "launch-fullscreen";
141    private ImageShow mImageShow = null;
142
143    private View mSaveButton = null;
144
145    private EditorPlaceHolder mEditorPlaceHolder = new EditorPlaceHolder(this);
146    private Editor mCurrentEditor = null;
147
148    private static final int SELECT_PICTURE = 1;
149    private static final String LOGTAG = "FilterShowActivity";
150
151    private boolean mShowingTinyPlanet = false;
152    private boolean mShowingImageStatePanel = false;
153    private boolean mShowingVersionsPanel = false;
154
155    private final Vector<ImageShow> mImageViews = new Vector<ImageShow>();
156
157    private ShareActionProvider mShareActionProvider;
158    private File mSharedOutputFile = null;
159
160    private boolean mSharingImage = false;
161
162    private WeakReference<ProgressDialog> mSavingProgressDialog;
163
164    private LoadBitmapTask mLoadBitmapTask;
165
166    private Uri mOriginalImageUri = null;
167    private ImagePreset mOriginalPreset = null;
168
169    private Uri mSelectedImageUri = null;
170
171    private ArrayList<Action> mActions = new ArrayList<Action>();
172    private UserPresetsManager mUserPresetsManager = null;
173    private UserPresetsAdapter mUserPresetsAdapter = null;
174    private CategoryAdapter mCategoryLooksAdapter = null;
175    private CategoryAdapter mCategoryBordersAdapter = null;
176    private CategoryAdapter mCategoryGeometryAdapter = null;
177    private CategoryAdapter mCategoryFiltersAdapter = null;
178    private CategoryAdapter mCategoryVersionsAdapter = null;
179    private int mCurrentPanel = MainPanel.LOOKS;
180    private Vector<FilterUserPresetRepresentation> mVersions =
181            new Vector<FilterUserPresetRepresentation>();
182    private int mVersionsCounter = 0;
183
184    private boolean mHandlingSwipeButton = false;
185    private View mHandledSwipeView = null;
186    private float mHandledSwipeViewLastDelta = 0;
187    private float mSwipeStartX = 0;
188    private float mSwipeStartY = 0;
189
190    private ProcessingService mBoundService;
191    private boolean mIsBound = false;
192    private Menu mMenu;
193    private DialogInterface mCurrentDialog = null;
194    private boolean mLoadingVisible = true;
195
196    public ProcessingService getProcessingService() {
197        return mBoundService;
198    }
199
200    public boolean isSimpleEditAction() {
201        return !PhotoPage.ACTION_NEXTGEN_EDIT.equalsIgnoreCase(mAction);
202    }
203
204    private ServiceConnection mConnection = new ServiceConnection() {
205        @Override
206        public void onServiceConnected(ComponentName className, IBinder service) {
207            /*
208             * This is called when the connection with the service has been
209             * established, giving us the service object we can use to
210             * interact with the service.  Because we have bound to a explicit
211             * service that we know is running in our own process, we can
212             * cast its IBinder to a concrete class and directly access it.
213             */
214            mBoundService = ((ProcessingService.LocalBinder)service).getService();
215            mBoundService.setFiltershowActivity(FilterShowActivity.this);
216            mBoundService.onStart();
217        }
218
219        @Override
220        public void onServiceDisconnected(ComponentName className) {
221            /*
222             * This is called when the connection with the service has been
223             * unexpectedly disconnected -- that is, its process crashed.
224             * Because it is running in our same process, we should never
225             * see this happen.
226             */
227            mBoundService = null;
228        }
229    };
230
231    void doBindService() {
232        /*
233         * Establish a connection with the service.  We use an explicit
234         * class name because we want a specific service implementation that
235         * we know will be running in our own process (and thus won't be
236         * supporting component replacement by other applications).
237         */
238        bindService(new Intent(FilterShowActivity.this, ProcessingService.class),
239                mConnection, Context.BIND_AUTO_CREATE);
240        mIsBound = true;
241    }
242
243    void doUnbindService() {
244        if (mIsBound) {
245            // Detach our existing connection.
246            unbindService(mConnection);
247            mIsBound = false;
248        }
249    }
250
251    public void updateUIAfterServiceStarted() {
252        MasterImage.setMaster(mMasterImage);
253        ImageFilter.setActivityForMemoryToasts(this);
254        mUserPresetsManager = new UserPresetsManager(this);
255        mUserPresetsAdapter = new UserPresetsAdapter(this);
256
257        setupMasterImage();
258        setupMenu();
259        setDefaultValues();
260        fillEditors();
261        getWindow().setBackgroundDrawable(new ColorDrawable(0));
262        loadXML();
263
264        fillCategories();
265        loadMainPanel();
266        extractXMPData();
267        processIntent();
268    }
269
270    @Override
271    public void onCreate(Bundle savedInstanceState) {
272        super.onCreate(savedInstanceState);
273
274        boolean onlyUsePortrait = getResources().getBoolean(R.bool.only_use_portrait);
275        if (onlyUsePortrait) {
276            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
277        }
278
279        clearGalleryBitmapPool();
280        doBindService();
281        getWindow().setBackgroundDrawable(new ColorDrawable(Color.GRAY));
282        setContentView(R.layout.filtershow_splashscreen);
283        UsageStatistics.onContentViewChanged(UsageStatistics.COMPONENT_EDITOR, "Main");
284        UsageStatistics.onEvent(UsageStatistics.COMPONENT_EDITOR,
285                UsageStatistics.CATEGORY_LIFECYCLE, UsageStatistics.LIFECYCLE_START);
286    }
287
288    public boolean isShowingImageStatePanel() {
289        return mShowingImageStatePanel;
290    }
291
292    public void loadMainPanel() {
293        if (findViewById(R.id.main_panel_container) == null) {
294            return;
295        }
296        MainPanel panel = new MainPanel();
297        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
298        transaction.replace(R.id.main_panel_container, panel, MainPanel.FRAGMENT_TAG);
299        transaction.commit();
300    }
301
302    public void loadEditorPanel(FilterRepresentation representation,
303                                final Editor currentEditor) {
304        if (representation.getEditorId() == ImageOnlyEditor.ID) {
305            currentEditor.reflectCurrentFilter();
306            return;
307        }
308        final int currentId = currentEditor.getID();
309        Runnable showEditor = new Runnable() {
310            @Override
311            public void run() {
312                EditorPanel panel = new EditorPanel();
313                panel.setEditor(currentId);
314                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
315                transaction.remove(getSupportFragmentManager().findFragmentByTag(MainPanel.FRAGMENT_TAG));
316                transaction.replace(R.id.main_panel_container, panel, MainPanel.FRAGMENT_TAG);
317                transaction.commit();
318            }
319        };
320        Fragment main = getSupportFragmentManager().findFragmentByTag(MainPanel.FRAGMENT_TAG);
321        boolean doAnimation = false;
322        if (mShowingImageStatePanel
323                && getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
324            doAnimation = true;
325        }
326        if (doAnimation && main != null && main instanceof MainPanel) {
327            MainPanel mainPanel = (MainPanel) main;
328            View container = mainPanel.getView().findViewById(R.id.category_panel_container);
329            View bottom = mainPanel.getView().findViewById(R.id.bottom_panel);
330            int panelHeight = container.getHeight() + bottom.getHeight();
331            ViewPropertyAnimator anim = mainPanel.getView().animate();
332            anim.translationY(panelHeight).start();
333            final Handler handler = new Handler();
334            handler.postDelayed(showEditor, anim.getDuration());
335        } else {
336            showEditor.run();
337        }
338    }
339
340    public void toggleInformationPanel() {
341        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
342        transaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left);
343
344        InfoPanel panel = new InfoPanel();
345        panel.show(transaction, InfoPanel.FRAGMENT_TAG);
346    }
347
348    private void loadXML() {
349        setContentView(R.layout.filtershow_activity);
350
351        ActionBar actionBar = getActionBar();
352        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
353        actionBar.setCustomView(R.layout.filtershow_actionbar);
354        actionBar.setBackgroundDrawable(new ColorDrawable(
355                getResources().getColor(R.color.background_screen)));
356
357        mSaveButton = actionBar.getCustomView();
358        mSaveButton.setOnClickListener(new OnClickListener() {
359            @Override
360            public void onClick(View view) {
361                saveImage();
362            }
363        });
364
365        mImageShow = (ImageShow) findViewById(R.id.imageShow);
366        mImageViews.add(mImageShow);
367
368        setupEditors();
369
370        mEditorPlaceHolder.hide();
371        mImageShow.attach();
372
373        setupStatePanel();
374    }
375
376    public void fillCategories() {
377        fillLooks();
378        loadUserPresets();
379        fillBorders();
380        fillTools();
381        fillEffects();
382        fillVersions();
383    }
384
385    public void setupStatePanel() {
386        MasterImage.getImage().setHistoryManager(mMasterImage.getHistory());
387    }
388
389    private void fillVersions() {
390        if (mCategoryVersionsAdapter != null) {
391            mCategoryVersionsAdapter.clear();
392        }
393        mCategoryVersionsAdapter = new CategoryAdapter(this);
394        mCategoryVersionsAdapter.setShowAddButton(true);
395    }
396
397    public void registerAction(Action action) {
398        if (mActions.contains(action)) {
399            return;
400        }
401        mActions.add(action);
402    }
403
404    private void loadActions() {
405        for (int i = 0; i < mActions.size(); i++) {
406            Action action = mActions.get(i);
407            action.setImageFrame(new Rect(0, 0, 96, 96), 0);
408        }
409    }
410
411    public void updateVersions() {
412        mCategoryVersionsAdapter.clear();
413        FilterUserPresetRepresentation originalRep = new FilterUserPresetRepresentation(
414                getString(R.string.filtershow_version_original), new ImagePreset(), -1);
415        mCategoryVersionsAdapter.add(
416                new Action(this, originalRep, Action.FULL_VIEW));
417        ImagePreset current = new ImagePreset(MasterImage.getImage().getPreset());
418        FilterUserPresetRepresentation currentRep = new FilterUserPresetRepresentation(
419                getString(R.string.filtershow_version_current), current, -1);
420        mCategoryVersionsAdapter.add(
421                new Action(this, currentRep, Action.FULL_VIEW));
422        if (mVersions.size() > 0) {
423            mCategoryVersionsAdapter.add(new Action(this, Action.SPACER));
424        }
425        for (FilterUserPresetRepresentation rep : mVersions) {
426            mCategoryVersionsAdapter.add(
427                    new Action(this, rep, Action.FULL_VIEW, true));
428        }
429        mCategoryVersionsAdapter.notifyDataSetInvalidated();
430    }
431
432    public void addCurrentVersion() {
433        ImagePreset current = new ImagePreset(MasterImage.getImage().getPreset());
434        mVersionsCounter++;
435        FilterUserPresetRepresentation rep = new FilterUserPresetRepresentation(
436                "" + mVersionsCounter, current, -1);
437        mVersions.add(rep);
438        updateVersions();
439    }
440
441    public void removeVersion(Action action) {
442        mVersions.remove(action.getRepresentation());
443        updateVersions();
444    }
445
446    public void removeLook(Action action) {
447        FilterUserPresetRepresentation rep =
448                (FilterUserPresetRepresentation) action.getRepresentation();
449        if (rep == null) {
450            return;
451        }
452        mUserPresetsManager.delete(rep.getId());
453        updateUserPresetsFromManager();
454    }
455
456    private void fillEffects() {
457        FiltersManager filtersManager = FiltersManager.getManager();
458        ArrayList<FilterRepresentation> filtersRepresentations = filtersManager.getEffects();
459        if (mCategoryFiltersAdapter != null) {
460            mCategoryFiltersAdapter.clear();
461        }
462        mCategoryFiltersAdapter = new CategoryAdapter(this);
463        for (FilterRepresentation representation : filtersRepresentations) {
464            if (representation.getTextId() != 0) {
465                representation.setName(getString(representation.getTextId()));
466            }
467            mCategoryFiltersAdapter.add(new Action(this, representation));
468        }
469    }
470
471    private void fillTools() {
472        FiltersManager filtersManager = FiltersManager.getManager();
473        ArrayList<FilterRepresentation> filtersRepresentations = filtersManager.getTools();
474        if (mCategoryGeometryAdapter != null) {
475            mCategoryGeometryAdapter.clear();
476        }
477        mCategoryGeometryAdapter = new CategoryAdapter(this);
478        boolean found = false;
479        for (FilterRepresentation representation : filtersRepresentations) {
480            mCategoryGeometryAdapter.add(new Action(this, representation));
481            if (representation instanceof FilterDrawRepresentation) {
482                found = true;
483            }
484        }
485        if (!found) {
486            FilterRepresentation representation = new FilterDrawRepresentation();
487            Action action = new Action(this, representation);
488            action.setIsDoubleAction(true);
489            mCategoryGeometryAdapter.add(action);
490        }
491    }
492
493    private void processIntent() {
494        Intent intent = getIntent();
495        if (intent.getBooleanExtra(LAUNCH_FULLSCREEN, false)) {
496            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
497        }
498
499        mAction = intent.getAction();
500        mSelectedImageUri = intent.getData();
501        Uri loadUri = mSelectedImageUri;
502        if (mOriginalImageUri != null) {
503            loadUri = mOriginalImageUri;
504        }
505        if (loadUri != null) {
506            startLoadBitmap(loadUri);
507        } else {
508            pickImage();
509        }
510    }
511
512    private void setupEditors() {
513        mEditorPlaceHolder.setContainer((FrameLayout) findViewById(R.id.editorContainer));
514        EditorManager.addEditors(mEditorPlaceHolder);
515        mEditorPlaceHolder.setOldViews(mImageViews);
516    }
517
518    private void fillEditors() {
519        mEditorPlaceHolder.addEditor(new EditorChanSat());
520        mEditorPlaceHolder.addEditor(new EditorGrad());
521        mEditorPlaceHolder.addEditor(new EditorDraw());
522        mEditorPlaceHolder.addEditor(new EditorColorBorder());
523        mEditorPlaceHolder.addEditor(new BasicEditor());
524        mEditorPlaceHolder.addEditor(new ImageOnlyEditor());
525        mEditorPlaceHolder.addEditor(new EditorTinyPlanet());
526        mEditorPlaceHolder.addEditor(new EditorRedEye());
527        mEditorPlaceHolder.addEditor(new EditorCrop());
528        mEditorPlaceHolder.addEditor(new EditorMirror());
529        mEditorPlaceHolder.addEditor(new EditorRotate());
530        mEditorPlaceHolder.addEditor(new EditorStraighten());
531    }
532
533    private void setDefaultValues() {
534        Resources res = getResources();
535
536        // TODO: get those values from XML.
537        FramedTextButton.setTextSize((int) getPixelsFromDip(14));
538        FramedTextButton.setTrianglePadding((int) getPixelsFromDip(4));
539        FramedTextButton.setTriangleSize((int) getPixelsFromDip(10));
540
541        Drawable curveHandle = res.getDrawable(R.drawable.camera_crop);
542        int curveHandleSize = (int) res.getDimension(R.dimen.crop_indicator_size);
543        Spline.setCurveHandle(curveHandle, curveHandleSize);
544        Spline.setCurveWidth((int) getPixelsFromDip(3));
545
546        mOriginalImageUri = null;
547    }
548
549    private void startLoadBitmap(Uri uri) {
550        final View imageShow = findViewById(R.id.imageShow);
551        imageShow.setVisibility(View.INVISIBLE);
552        startLoadingIndicator();
553        mShowingTinyPlanet = false;
554        mLoadBitmapTask = new LoadBitmapTask();
555        mLoadBitmapTask.execute(uri);
556    }
557
558    private void fillBorders() {
559        FiltersManager filtersManager = FiltersManager.getManager();
560        ArrayList<FilterRepresentation> borders = filtersManager.getBorders();
561
562        for (int i = 0; i < borders.size(); i++) {
563            FilterRepresentation filter = borders.get(i);
564            filter.setName(getString(R.string.borders));
565            if (i == 0) {
566                filter.setName(getString(R.string.none));
567            }
568        }
569
570        if (mCategoryBordersAdapter != null) {
571            mCategoryBordersAdapter.clear();
572        }
573        mCategoryBordersAdapter = new CategoryAdapter(this);
574        for (FilterRepresentation representation : borders) {
575            if (representation.getTextId() != 0) {
576                representation.setName(getString(representation.getTextId()));
577            }
578            mCategoryBordersAdapter.add(new Action(this, representation, Action.FULL_VIEW));
579        }
580    }
581
582    public UserPresetsAdapter getUserPresetsAdapter() {
583        return mUserPresetsAdapter;
584    }
585
586    public CategoryAdapter getCategoryLooksAdapter() {
587        return mCategoryLooksAdapter;
588    }
589
590    public CategoryAdapter getCategoryBordersAdapter() {
591        return mCategoryBordersAdapter;
592    }
593
594    public CategoryAdapter getCategoryGeometryAdapter() {
595        return mCategoryGeometryAdapter;
596    }
597
598    public CategoryAdapter getCategoryFiltersAdapter() {
599        return mCategoryFiltersAdapter;
600    }
601
602    public CategoryAdapter getCategoryVersionsAdapter() {
603        return mCategoryVersionsAdapter;
604    }
605
606    public void removeFilterRepresentation(FilterRepresentation filterRepresentation) {
607        if (filterRepresentation == null) {
608            return;
609        }
610        ImagePreset oldPreset = MasterImage.getImage().getPreset();
611        ImagePreset copy = new ImagePreset(oldPreset);
612        copy.removeFilter(filterRepresentation);
613        MasterImage.getImage().setPreset(copy, copy.getLastRepresentation(), true);
614        if (MasterImage.getImage().getCurrentFilterRepresentation() == filterRepresentation) {
615            FilterRepresentation lastRepresentation = copy.getLastRepresentation();
616            MasterImage.getImage().setCurrentFilterRepresentation(lastRepresentation);
617        }
618    }
619
620    public void useFilterRepresentation(FilterRepresentation filterRepresentation) {
621        if (filterRepresentation == null) {
622            return;
623        }
624        if (!(filterRepresentation instanceof FilterRotateRepresentation)
625            && !(filterRepresentation instanceof FilterMirrorRepresentation)
626            && MasterImage.getImage().getCurrentFilterRepresentation() == filterRepresentation) {
627            return;
628        }
629        if (filterRepresentation instanceof FilterUserPresetRepresentation
630                || filterRepresentation instanceof FilterRotateRepresentation
631                || filterRepresentation instanceof FilterMirrorRepresentation) {
632            MasterImage.getImage().onNewLook(filterRepresentation);
633        }
634        ImagePreset oldPreset = MasterImage.getImage().getPreset();
635        ImagePreset copy = new ImagePreset(oldPreset);
636        FilterRepresentation representation = copy.getRepresentation(filterRepresentation);
637        if (representation == null) {
638            filterRepresentation = filterRepresentation.copy();
639            copy.addFilter(filterRepresentation);
640        } else {
641            if (filterRepresentation.allowsSingleInstanceOnly()) {
642                // Don't just update the filter representation. Centralize the
643                // logic in the addFilter(), such that we can keep "None" as
644                // null.
645                if (!representation.equals(filterRepresentation)) {
646                    // Only do this if the filter isn't the same
647                    // (state panel clicks can lead us here)
648                    copy.removeFilter(representation);
649                    copy.addFilter(filterRepresentation);
650                }
651            }
652        }
653        MasterImage.getImage().setPreset(copy, filterRepresentation, true);
654        MasterImage.getImage().setCurrentFilterRepresentation(filterRepresentation);
655    }
656
657    public void showRepresentation(FilterRepresentation representation) {
658        if (representation == null) {
659            return;
660        }
661
662        if (representation instanceof FilterRotateRepresentation) {
663            FilterRotateRepresentation r = (FilterRotateRepresentation) representation;
664            r.rotateCW();
665        }
666        if (representation instanceof FilterMirrorRepresentation) {
667            FilterMirrorRepresentation r = (FilterMirrorRepresentation) representation;
668            r.cycle();
669        }
670        if (representation.isBooleanFilter()) {
671            ImagePreset preset = MasterImage.getImage().getPreset();
672            if (preset.getRepresentation(representation) != null) {
673                // remove
674                ImagePreset copy = new ImagePreset(preset);
675                copy.removeFilter(representation);
676                FilterRepresentation filterRepresentation = representation.copy();
677                MasterImage.getImage().setPreset(copy, filterRepresentation, true);
678                MasterImage.getImage().setCurrentFilterRepresentation(null);
679                return;
680            }
681        }
682        useFilterRepresentation(representation);
683
684        // show representation
685        if (mCurrentEditor != null) {
686            mCurrentEditor.detach();
687        }
688        mCurrentEditor = mEditorPlaceHolder.showEditor(representation.getEditorId());
689        loadEditorPanel(representation, mCurrentEditor);
690    }
691
692    public Editor getEditor(int editorID) {
693        return mEditorPlaceHolder.getEditor(editorID);
694    }
695
696    public void setCurrentPanel(int currentPanel) {
697        mCurrentPanel = currentPanel;
698    }
699
700    public int getCurrentPanel() {
701        return mCurrentPanel;
702    }
703
704    public void updateCategories() {
705        ImagePreset preset = mMasterImage.getPreset();
706        mCategoryLooksAdapter.reflectImagePreset(preset);
707        mCategoryBordersAdapter.reflectImagePreset(preset);
708    }
709
710    public View getMainStatePanelContainer(int id) {
711        return findViewById(id);
712    }
713
714    @Override
715    public void onShow(DialogInterface dialog) {
716        mCurrentDialog = dialog;
717    }
718
719    @Override
720    public void onDismiss(DialogInterface dialogInterface) {
721        mCurrentDialog = null;
722    }
723
724    private class LoadHighresBitmapTask extends AsyncTask<Void, Void, Boolean> {
725        @Override
726        protected Boolean doInBackground(Void... params) {
727            MasterImage master = MasterImage.getImage();
728            Rect originalBounds = master.getOriginalBounds();
729            if (master.supportsHighRes()) {
730                int highresPreviewSize = master.getOriginalBitmapLarge().getWidth() * 2;
731                if (highresPreviewSize > originalBounds.width()) {
732                    highresPreviewSize = originalBounds.width();
733                }
734                Rect bounds = new Rect();
735                Bitmap originalHires = ImageLoader.loadOrientedConstrainedBitmap(master.getUri(),
736                        master.getActivity(), highresPreviewSize,
737                        master.getOrientation(), bounds);
738                master.setOriginalBounds(bounds);
739                master.setOriginalBitmapHighres(originalHires);
740                mBoundService.setOriginalBitmapHighres(originalHires);
741                master.warnListeners();
742            }
743            return true;
744        }
745
746        @Override
747        protected void onPostExecute(Boolean result) {
748            Bitmap highresBitmap = MasterImage.getImage().getOriginalBitmapHighres();
749            if (highresBitmap != null) {
750                float highResPreviewScale = (float) highresBitmap.getWidth()
751                        / (float) MasterImage.getImage().getOriginalBounds().width();
752                mBoundService.setHighresPreviewScaleFactor(highResPreviewScale);
753            }
754            MasterImage.getImage().warnListeners();
755        }
756    }
757
758    public boolean isLoadingVisible() {
759        return mLoadingVisible;
760    }
761
762    public void startLoadingIndicator() {
763        final View loading = findViewById(R.id.loading);
764        mLoadingVisible = true;
765        loading.setVisibility(View.VISIBLE);
766    }
767
768    public void stopLoadingIndicator() {
769        final View loading = findViewById(R.id.loading);
770        loading.setVisibility(View.GONE);
771        mLoadingVisible = false;
772    }
773
774    private class LoadBitmapTask extends AsyncTask<Uri, Boolean, Boolean> {
775        int mBitmapSize;
776
777        public LoadBitmapTask() {
778            mBitmapSize = getScreenImageSize();
779        }
780
781        @Override
782        protected Boolean doInBackground(Uri... params) {
783            if (!MasterImage.getImage().loadBitmap(params[0], mBitmapSize)) {
784                return false;
785            }
786            publishProgress(ImageLoader.queryLightCycle360(MasterImage.getImage().getActivity()));
787            return true;
788        }
789
790        @Override
791        protected void onProgressUpdate(Boolean... values) {
792            super.onProgressUpdate(values);
793            if (isCancelled()) {
794                return;
795            }
796            if (values[0]) {
797                mShowingTinyPlanet = true;
798            }
799        }
800
801        @Override
802        protected void onPostExecute(Boolean result) {
803            MasterImage.setMaster(mMasterImage);
804            if (isCancelled()) {
805                return;
806            }
807
808            if (!result) {
809                if (mOriginalImageUri != null
810                        && !mOriginalImageUri.equals(mSelectedImageUri)) {
811                    mOriginalImageUri = mSelectedImageUri;
812                    mOriginalPreset = null;
813                    Toast.makeText(FilterShowActivity.this,
814                            R.string.cannot_edit_original, Toast.LENGTH_SHORT).show();
815                    startLoadBitmap(mOriginalImageUri);
816                } else {
817                    cannotLoadImage();
818                }
819                return;
820            }
821
822            if (null == CachingPipeline.getRenderScriptContext()){
823                Log.v(LOGTAG,"RenderScript context destroyed during load");
824                return;
825            }
826            final View imageShow = findViewById(R.id.imageShow);
827            imageShow.setVisibility(View.VISIBLE);
828
829
830            Bitmap largeBitmap = MasterImage.getImage().getOriginalBitmapLarge();
831            mBoundService.setOriginalBitmap(largeBitmap);
832
833            float previewScale = (float) largeBitmap.getWidth()
834                    / (float) MasterImage.getImage().getOriginalBounds().width();
835            mBoundService.setPreviewScaleFactor(previewScale);
836            if (!mShowingTinyPlanet) {
837                mCategoryFiltersAdapter.removeTinyPlanet();
838            }
839            mCategoryLooksAdapter.imageLoaded();
840            mCategoryBordersAdapter.imageLoaded();
841            mCategoryGeometryAdapter.imageLoaded();
842            mCategoryFiltersAdapter.imageLoaded();
843            mLoadBitmapTask = null;
844
845            MasterImage.getImage().warnListeners();
846            loadActions();
847
848            if (mOriginalPreset != null) {
849                MasterImage.getImage().setLoadedPreset(mOriginalPreset);
850                MasterImage.getImage().setPreset(mOriginalPreset,
851                        mOriginalPreset.getLastRepresentation(), true);
852                mOriginalPreset = null;
853            } else {
854                setDefaultPreset();
855            }
856
857            MasterImage.getImage().resetGeometryImages(true);
858
859            if (mAction == TINY_PLANET_ACTION) {
860                showRepresentation(mCategoryFiltersAdapter.getTinyPlanet());
861            }
862            LoadHighresBitmapTask highresLoad = new LoadHighresBitmapTask();
863            highresLoad.execute();
864            MasterImage.getImage().warnListeners();
865            super.onPostExecute(result);
866        }
867
868    }
869
870    private void clearGalleryBitmapPool() {
871        (new AsyncTask<Void, Void, Void>() {
872            @Override
873            protected Void doInBackground(Void... params) {
874                // Free memory held in Gallery's Bitmap pool.  May be O(n) for n bitmaps.
875                GalleryBitmapPool.getInstance().clear();
876                return null;
877            }
878        }).execute();
879    }
880
881    @Override
882    protected void onDestroy() {
883        if (mLoadBitmapTask != null) {
884            mLoadBitmapTask.cancel(false);
885        }
886        mUserPresetsManager.close();
887        doUnbindService();
888        super.onDestroy();
889    }
890
891    // TODO: find a more robust way of handling image size selection
892    // for high screen densities.
893    private int getScreenImageSize() {
894        DisplayMetrics outMetrics = new DisplayMetrics();
895        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
896        return Math.max(outMetrics.heightPixels, outMetrics.widthPixels);
897    }
898
899    private void showSavingProgress(String albumName) {
900        ProgressDialog progress;
901        if (mSavingProgressDialog != null) {
902            progress = mSavingProgressDialog.get();
903            if (progress != null) {
904                progress.show();
905                return;
906            }
907        }
908        // TODO: Allow cancellation of the saving process
909        String progressText;
910        if (albumName == null) {
911            progressText = getString(R.string.saving_image);
912        } else {
913            progressText = getString(R.string.filtershow_saving_image, albumName);
914        }
915        progress = ProgressDialog.show(this, "", progressText, true, false);
916        mSavingProgressDialog = new WeakReference<ProgressDialog>(progress);
917    }
918
919    private void hideSavingProgress() {
920        if (mSavingProgressDialog != null) {
921            ProgressDialog progress = mSavingProgressDialog.get();
922            if (progress != null)
923                progress.dismiss();
924        }
925    }
926
927    public void completeSaveImage(Uri saveUri) {
928        if (mSharingImage && mSharedOutputFile != null) {
929            // Image saved, we unblock the content provider
930            Uri uri = Uri.withAppendedPath(SharedImageProvider.CONTENT_URI,
931                    Uri.encode(mSharedOutputFile.getAbsolutePath()));
932            ContentValues values = new ContentValues();
933            values.put(SharedImageProvider.PREPARE, false);
934            getContentResolver().insert(uri, values);
935        }
936        setResult(RESULT_OK, new Intent().setData(saveUri));
937        hideSavingProgress();
938        finish();
939    }
940
941    @Override
942    public boolean onShareTargetSelected(ShareActionProvider arg0, Intent arg1) {
943        // First, let's tell the SharedImageProvider that it will need to wait
944        // for the image
945        Uri uri = Uri.withAppendedPath(SharedImageProvider.CONTENT_URI,
946                Uri.encode(mSharedOutputFile.getAbsolutePath()));
947        ContentValues values = new ContentValues();
948        values.put(SharedImageProvider.PREPARE, true);
949        getContentResolver().insert(uri, values);
950        mSharingImage = true;
951
952        // Process and save the image in the background.
953        showSavingProgress(null);
954        mImageShow.saveImage(this, mSharedOutputFile);
955        return true;
956    }
957
958    private Intent getDefaultShareIntent() {
959        Intent intent = new Intent(Intent.ACTION_SEND);
960        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
961        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
962        intent.setType(SharedImageProvider.MIME_TYPE);
963        mSharedOutputFile = SaveImage.getNewFile(this, MasterImage.getImage().getUri());
964        Uri uri = Uri.withAppendedPath(SharedImageProvider.CONTENT_URI,
965                Uri.encode(mSharedOutputFile.getAbsolutePath()));
966        intent.putExtra(Intent.EXTRA_STREAM, uri);
967        return intent;
968    }
969
970    @Override
971    public boolean onCreateOptionsMenu(Menu menu) {
972        getMenuInflater().inflate(R.menu.filtershow_activity_menu, menu);
973        MenuItem showState = menu.findItem(R.id.showImageStateButton);
974        if (mShowingImageStatePanel) {
975            showState.setTitle(R.string.hide_imagestate_panel);
976        } else {
977            showState.setTitle(R.string.show_imagestate_panel);
978        }
979        mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.menu_share)
980                .getActionProvider();
981        mShareActionProvider.setShareIntent(getDefaultShareIntent());
982        mShareActionProvider.setOnShareTargetSelectedListener(this);
983        mMenu = menu;
984        setupMenu();
985        return true;
986    }
987
988    private void setupMenu(){
989        if (mMenu == null || mMasterImage == null) {
990            return;
991        }
992        MenuItem undoItem = mMenu.findItem(R.id.undoButton);
993        MenuItem redoItem = mMenu.findItem(R.id.redoButton);
994        MenuItem resetItem = mMenu.findItem(R.id.resetHistoryButton);
995        mMasterImage.getHistory().setMenuItems(undoItem, redoItem, resetItem);
996    }
997
998    @Override
999    public void onPause() {
1000        super.onPause();
1001        if (mShareActionProvider != null) {
1002            mShareActionProvider.setOnShareTargetSelectedListener(null);
1003        }
1004    }
1005
1006    @Override
1007    public void onResume() {
1008        super.onResume();
1009        if (mShareActionProvider != null) {
1010            mShareActionProvider.setOnShareTargetSelectedListener(this);
1011        }
1012    }
1013
1014    @Override
1015    public boolean onOptionsItemSelected(MenuItem item) {
1016        switch (item.getItemId()) {
1017            case R.id.undoButton: {
1018                HistoryManager adapter = mMasterImage.getHistory();
1019                int position = adapter.undo();
1020                mMasterImage.onHistoryItemClick(position);
1021                backToMain();
1022                invalidateViews();
1023                UsageStatistics.onEvent(UsageStatistics.COMPONENT_EDITOR,
1024                        UsageStatistics.CATEGORY_BUTTON_PRESS, "Undo");
1025                return true;
1026            }
1027            case R.id.redoButton: {
1028                HistoryManager adapter = mMasterImage.getHistory();
1029                int position = adapter.redo();
1030                mMasterImage.onHistoryItemClick(position);
1031                invalidateViews();
1032                UsageStatistics.onEvent(UsageStatistics.COMPONENT_EDITOR,
1033                        UsageStatistics.CATEGORY_BUTTON_PRESS, "Redo");
1034                return true;
1035            }
1036            case R.id.resetHistoryButton: {
1037                resetHistory();
1038                UsageStatistics.onEvent(UsageStatistics.COMPONENT_EDITOR,
1039                        UsageStatistics.CATEGORY_BUTTON_PRESS, "ResetHistory");
1040                return true;
1041            }
1042            case R.id.showImageStateButton: {
1043                toggleImageStatePanel();
1044                UsageStatistics.onEvent(UsageStatistics.COMPONENT_EDITOR,
1045                        UsageStatistics.CATEGORY_BUTTON_PRESS,
1046                        mShowingImageStatePanel ? "ShowPanel" : "HidePanel");
1047                return true;
1048            }
1049            case R.id.exportFlattenButton: {
1050                showExportOptionsDialog();
1051                return true;
1052            }
1053            case android.R.id.home: {
1054                saveImage();
1055                return true;
1056            }
1057            case R.id.manageUserPresets: {
1058                manageUserPresets();
1059                return true;
1060            }
1061            case R.id.showInfoPanel: {
1062                toggleInformationPanel();
1063                return true;
1064            }
1065            case R.id.printButton: {
1066                print();
1067                return true;
1068            }
1069        }
1070        return false;
1071    }
1072
1073    public void print() {
1074        Bitmap bitmap = MasterImage.getImage().getHighresImage();
1075        PrintJob.printBitmap(this, "ImagePrint", bitmap);
1076    }
1077
1078    public void addNewPreset() {
1079        DialogFragment dialog = new PresetManagementDialog();
1080        dialog.show(getSupportFragmentManager(), "NoticeDialogFragment");
1081    }
1082
1083    private void manageUserPresets() {
1084        DialogFragment dialog = new PresetManagementDialog();
1085        dialog.show(getSupportFragmentManager(), "NoticeDialogFragment");
1086    }
1087
1088    private void showExportOptionsDialog() {
1089        DialogFragment dialog = new ExportDialog();
1090        dialog.show(getSupportFragmentManager(), "ExportDialogFragment");
1091    }
1092
1093    public void updateUserPresetsFromAdapter(UserPresetsAdapter adapter) {
1094        ArrayList<FilterUserPresetRepresentation> representations =
1095                adapter.getDeletedRepresentations();
1096        for (FilterUserPresetRepresentation representation : representations) {
1097            deletePreset(representation.getId());
1098        }
1099        ArrayList<FilterUserPresetRepresentation> changedRepresentations =
1100                adapter.getChangedRepresentations();
1101        for (FilterUserPresetRepresentation representation : changedRepresentations) {
1102            updatePreset(representation);
1103        }
1104        adapter.clearDeletedRepresentations();
1105        adapter.clearChangedRepresentations();
1106        loadUserPresets();
1107    }
1108
1109    public void loadUserPresets() {
1110        mUserPresetsManager.load();
1111        updateUserPresetsFromManager();
1112    }
1113
1114    public void updateUserPresetsFromManager() {
1115        ArrayList<FilterUserPresetRepresentation> presets = mUserPresetsManager.getRepresentations();
1116        if (presets == null) {
1117            return;
1118        }
1119        if (mCategoryLooksAdapter != null) {
1120            fillLooks();
1121        }
1122        if (presets.size() > 0) {
1123            mCategoryLooksAdapter.add(new Action(this, Action.SPACER));
1124        }
1125        mUserPresetsAdapter.clear();
1126        for (int i = 0; i < presets.size(); i++) {
1127            FilterUserPresetRepresentation representation = presets.get(i);
1128            mCategoryLooksAdapter.add(
1129                    new Action(this, representation, Action.FULL_VIEW, true));
1130            mUserPresetsAdapter.add(new Action(this, representation, Action.FULL_VIEW));
1131        }
1132        if (presets.size() > 0) {
1133            mCategoryLooksAdapter.add(new Action(this, Action.ADD_ACTION));
1134        }
1135        mCategoryLooksAdapter.notifyDataSetChanged();
1136        mCategoryLooksAdapter.notifyDataSetInvalidated();
1137    }
1138
1139    public void saveCurrentImagePreset(String name) {
1140        mUserPresetsManager.save(MasterImage.getImage().getPreset(), name);
1141    }
1142
1143    private void deletePreset(int id) {
1144        mUserPresetsManager.delete(id);
1145    }
1146
1147    private void updatePreset(FilterUserPresetRepresentation representation) {
1148        mUserPresetsManager.update(representation);
1149    }
1150
1151    public void enableSave(boolean enable) {
1152        if (mSaveButton != null) {
1153            mSaveButton.setEnabled(enable);
1154        }
1155    }
1156
1157    private void fillLooks() {
1158        FiltersManager filtersManager = FiltersManager.getManager();
1159        ArrayList<FilterRepresentation> filtersRepresentations = filtersManager.getLooks();
1160
1161        if (mCategoryLooksAdapter != null) {
1162            mCategoryLooksAdapter.clear();
1163        }
1164        mCategoryLooksAdapter = new CategoryAdapter(this);
1165        int verticalItemHeight = (int) getResources().getDimension(R.dimen.action_item_height);
1166        mCategoryLooksAdapter.setItemHeight(verticalItemHeight);
1167        for (FilterRepresentation representation : filtersRepresentations) {
1168            mCategoryLooksAdapter.add(new Action(this, representation, Action.FULL_VIEW));
1169        }
1170        if (mUserPresetsManager.getRepresentations() == null
1171            || mUserPresetsManager.getRepresentations().size() == 0) {
1172            mCategoryLooksAdapter.add(new Action(this, Action.ADD_ACTION));
1173        }
1174
1175        Fragment panel = getSupportFragmentManager().findFragmentByTag(MainPanel.FRAGMENT_TAG);
1176        if (panel != null) {
1177            if (panel instanceof MainPanel) {
1178                MainPanel mainPanel = (MainPanel) panel;
1179                mainPanel.loadCategoryLookPanel(true);
1180            }
1181        }
1182    }
1183
1184    public void setDefaultPreset() {
1185        // Default preset (original)
1186        ImagePreset preset = new ImagePreset(); // empty
1187        mMasterImage.setPreset(preset, preset.getLastRepresentation(), true);
1188    }
1189
1190    // //////////////////////////////////////////////////////////////////////////////
1191    // Some utility functions
1192    // TODO: finish the cleanup.
1193
1194    public void invalidateViews() {
1195        for (ImageShow views : mImageViews) {
1196            views.updateImage();
1197        }
1198    }
1199
1200    public void hideImageViews() {
1201        for (View view : mImageViews) {
1202            view.setVisibility(View.GONE);
1203        }
1204        mEditorPlaceHolder.hide();
1205    }
1206
1207    // //////////////////////////////////////////////////////////////////////////////
1208    // imageState panel...
1209
1210    public void toggleImageStatePanel() {
1211        invalidateOptionsMenu();
1212        mShowingImageStatePanel = !mShowingImageStatePanel;
1213        Fragment panel = getSupportFragmentManager().findFragmentByTag(MainPanel.FRAGMENT_TAG);
1214        if (panel != null) {
1215            if (panel instanceof EditorPanel) {
1216                EditorPanel editorPanel = (EditorPanel) panel;
1217                editorPanel.showImageStatePanel(mShowingImageStatePanel);
1218            } else if (panel instanceof MainPanel) {
1219                MainPanel mainPanel = (MainPanel) panel;
1220                mainPanel.showImageStatePanel(mShowingImageStatePanel);
1221            }
1222        }
1223    }
1224
1225    public void toggleVersionsPanel() {
1226        mShowingVersionsPanel = !mShowingVersionsPanel;
1227        Fragment panel = getSupportFragmentManager().findFragmentByTag(MainPanel.FRAGMENT_TAG);
1228        if (panel != null && panel instanceof MainPanel) {
1229            MainPanel mainPanel = (MainPanel) panel;
1230            mainPanel.loadCategoryVersionsPanel();
1231        }
1232    }
1233
1234    @Override
1235    public void onConfigurationChanged(Configuration newConfig)
1236    {
1237        super.onConfigurationChanged(newConfig);
1238
1239        setDefaultValues();
1240        if (mMasterImage == null) {
1241            return;
1242        }
1243        loadXML();
1244        fillCategories();
1245        loadMainPanel();
1246
1247        if (mCurrentDialog != null) {
1248            mCurrentDialog.dismiss();
1249            mCurrentDialog = null;
1250        }
1251        // mLoadBitmapTask==null implies you have looked at the intent
1252        if (!mShowingTinyPlanet && (mLoadBitmapTask == null)) {
1253            mCategoryFiltersAdapter.removeTinyPlanet();
1254        }
1255        stopLoadingIndicator();
1256    }
1257
1258    public void setupMasterImage() {
1259
1260        HistoryManager historyManager = new HistoryManager();
1261        StateAdapter imageStateAdapter = new StateAdapter(this, 0);
1262        MasterImage.reset();
1263        mMasterImage = MasterImage.getImage();
1264        mMasterImage.setHistoryManager(historyManager);
1265        mMasterImage.setStateAdapter(imageStateAdapter);
1266        mMasterImage.setActivity(this);
1267
1268        if (Runtime.getRuntime().maxMemory() > LIMIT_SUPPORTS_HIGHRES) {
1269            mMasterImage.setSupportsHighRes(true);
1270        } else {
1271            mMasterImage.setSupportsHighRes(false);
1272        }
1273    }
1274
1275    void resetHistory() {
1276        HistoryManager adapter = mMasterImage.getHistory();
1277        adapter.reset();
1278        HistoryItem historyItem = adapter.getItem(0);
1279        ImagePreset original = new ImagePreset(historyItem.getImagePreset());
1280        mMasterImage.setPreset(original, historyItem.getFilterRepresentation(), true);
1281        invalidateViews();
1282        backToMain();
1283    }
1284
1285    public void showDefaultImageView() {
1286        mEditorPlaceHolder.hide();
1287        mImageShow.setVisibility(View.VISIBLE);
1288        MasterImage.getImage().setCurrentFilter(null);
1289        MasterImage.getImage().setCurrentFilterRepresentation(null);
1290    }
1291
1292    public void backToMain() {
1293        Fragment currentPanel = getSupportFragmentManager().findFragmentByTag(MainPanel.FRAGMENT_TAG);
1294        if (currentPanel instanceof MainPanel) {
1295            return;
1296        }
1297        loadMainPanel();
1298        showDefaultImageView();
1299    }
1300
1301    @Override
1302    public void onBackPressed() {
1303        Fragment currentPanel = getSupportFragmentManager().findFragmentByTag(MainPanel.FRAGMENT_TAG);
1304        if (currentPanel instanceof MainPanel) {
1305            if (!mImageShow.hasModifications()) {
1306                done();
1307            } else {
1308                AlertDialog.Builder builder = new AlertDialog.Builder(this);
1309                builder.setMessage(R.string.unsaved).setTitle(R.string.save_before_exit);
1310                builder.setPositiveButton(R.string.save_and_exit, new DialogInterface.OnClickListener() {
1311                    @Override
1312                    public void onClick(DialogInterface dialog, int id) {
1313                        saveImage();
1314                    }
1315                });
1316                builder.setNegativeButton(R.string.exit, new DialogInterface.OnClickListener() {
1317                    @Override
1318                    public void onClick(DialogInterface dialog, int id) {
1319                        done();
1320                    }
1321                });
1322                builder.show();
1323            }
1324        } else {
1325            backToMain();
1326        }
1327    }
1328
1329    public void cannotLoadImage() {
1330        Toast.makeText(this, R.string.cannot_load_image, Toast.LENGTH_SHORT).show();
1331        finish();
1332    }
1333
1334    // //////////////////////////////////////////////////////////////////////////////
1335
1336    public float getPixelsFromDip(float value) {
1337        Resources r = getResources();
1338        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value,
1339                r.getDisplayMetrics());
1340    }
1341
1342    @Override
1343    public void onItemClick(AdapterView<?> parent, View view, int position,
1344            long id) {
1345        mMasterImage.onHistoryItemClick(position);
1346        invalidateViews();
1347    }
1348
1349    public void pickImage() {
1350        Intent intent = new Intent();
1351        intent.setType("image/*");
1352        intent.setAction(Intent.ACTION_GET_CONTENT);
1353        startActivityForResult(Intent.createChooser(intent, getString(R.string.select_image)),
1354                SELECT_PICTURE);
1355    }
1356
1357    @Override
1358    public void onActivityResult(int requestCode, int resultCode, Intent data) {
1359        if (resultCode == RESULT_OK) {
1360            if (requestCode == SELECT_PICTURE) {
1361                Uri selectedImageUri = data.getData();
1362                startLoadBitmap(selectedImageUri);
1363            }
1364        }
1365    }
1366
1367
1368    public void saveImage() {
1369        if (mImageShow.hasModifications()) {
1370            // Get the name of the album, to which the image will be saved
1371            File saveDir = SaveImage.getFinalSaveDirectory(this, mSelectedImageUri);
1372            int bucketId = GalleryUtils.getBucketId(saveDir.getPath());
1373            String albumName = LocalAlbum.getLocalizedName(getResources(), bucketId, null);
1374            showSavingProgress(albumName);
1375            mImageShow.saveImage(this, null);
1376        } else {
1377            done();
1378        }
1379    }
1380
1381
1382    public void done() {
1383        hideSavingProgress();
1384        if (mLoadBitmapTask != null) {
1385            mLoadBitmapTask.cancel(false);
1386        }
1387        finish();
1388    }
1389
1390    private void extractXMPData() {
1391        XMresults res = XmpPresets.extractXMPData(
1392                getBaseContext(), mMasterImage, getIntent().getData());
1393        if (res == null)
1394            return;
1395
1396        mOriginalImageUri = res.originalimage;
1397        mOriginalPreset = res.preset;
1398    }
1399
1400    public Uri getSelectedImageUri() {
1401        return mSelectedImageUri;
1402    }
1403
1404    public void setHandlesSwipeForView(View view, float startX, float startY) {
1405        if (view != null) {
1406            mHandlingSwipeButton = true;
1407        } else {
1408            mHandlingSwipeButton = false;
1409        }
1410        mHandledSwipeView = view;
1411        int[] location = new int[2];
1412        view.getLocationInWindow(location);
1413        mSwipeStartX = location[0] + startX;
1414        mSwipeStartY = location[1] + startY;
1415    }
1416
1417    public boolean dispatchTouchEvent (MotionEvent ev) {
1418        if (mHandlingSwipeButton) {
1419            int direction = CategoryView.HORIZONTAL;
1420            if (mHandledSwipeView instanceof CategoryView) {
1421                direction = ((CategoryView) mHandledSwipeView).getOrientation();
1422            }
1423            if (ev.getActionMasked() == MotionEvent.ACTION_MOVE) {
1424                float delta = ev.getY() - mSwipeStartY;
1425                float distance = mHandledSwipeView.getHeight();
1426                if (direction == CategoryView.VERTICAL) {
1427                    delta = ev.getX() - mSwipeStartX;
1428                    mHandledSwipeView.setTranslationX(delta);
1429                    distance = mHandledSwipeView.getWidth();
1430                } else {
1431                    mHandledSwipeView.setTranslationY(delta);
1432                }
1433                delta = Math.abs(delta);
1434                float transparency = Math.min(1, delta / distance);
1435                mHandledSwipeView.setAlpha(1.f - transparency);
1436                mHandledSwipeViewLastDelta = delta;
1437            }
1438            if (ev.getActionMasked() == MotionEvent.ACTION_CANCEL
1439                    || ev.getActionMasked() == MotionEvent.ACTION_UP) {
1440                mHandledSwipeView.setTranslationX(0);
1441                mHandledSwipeView.setTranslationY(0);
1442                mHandledSwipeView.setAlpha(1.f);
1443                mHandlingSwipeButton = false;
1444                float distance = mHandledSwipeView.getHeight();
1445                if (direction == CategoryView.VERTICAL) {
1446                    distance = mHandledSwipeView.getWidth();
1447                }
1448                if (mHandledSwipeViewLastDelta > distance) {
1449                    ((SwipableView) mHandledSwipeView).delete();
1450                }
1451            }
1452            return true;
1453        }
1454        return super.dispatchTouchEvent(ev);
1455    }
1456
1457    public Point mHintTouchPoint = new Point();
1458
1459    public Point hintTouchPoint(View view) {
1460        int location[] = new int[2];
1461        view.getLocationOnScreen(location);
1462        int x = mHintTouchPoint.x - location[0];
1463        int y = mHintTouchPoint.y - location[1];
1464        return new Point(x, y);
1465    }
1466
1467    public void startTouchAnimation(View target, float x, float y) {
1468        final CategorySelected hint =
1469                (CategorySelected) findViewById(R.id.categorySelectedIndicator);
1470        int location[] = new int[2];
1471        target.getLocationOnScreen(location);
1472        mHintTouchPoint.x = (int) (location[0] + x);
1473        mHintTouchPoint.y = (int) (location[1] + y);
1474        int locationHint[] = new int[2];
1475        ((View)hint.getParent()).getLocationOnScreen(locationHint);
1476        int dx = (int) (x - (hint.getWidth())/2);
1477        int dy = (int) (y - (hint.getHeight())/2);
1478        hint.setTranslationX(location[0] - locationHint[0] + dx);
1479        hint.setTranslationY(location[1] - locationHint[1] + dy);
1480        hint.setVisibility(View.VISIBLE);
1481        hint.animate().scaleX(2).scaleY(2).alpha(0).withEndAction(new Runnable() {
1482            @Override
1483            public void run() {
1484                hint.setVisibility(View.INVISIBLE);
1485                hint.setScaleX(1);
1486                hint.setScaleY(1);
1487                hint.setAlpha(1);
1488            }
1489        });
1490    }
1491}
1492