OSDN Git Service

Merge "Fix crash / jank / presets add" into gb-ub-photos-carlsbad
[android-x86/packages-apps-Gallery2.git] / src / com / android / gallery3d / ui / MenuExecutor.java
1 /*
2  * Copyright (C) 2010 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
17 package com.android.gallery3d.ui;
18
19 import android.app.Activity;
20 import android.app.AlertDialog;
21 import android.app.ProgressDialog;
22 import android.content.Context;
23 import android.content.DialogInterface;
24 import android.content.DialogInterface.OnCancelListener;
25 import android.content.DialogInterface.OnClickListener;
26 import android.content.Intent;
27 import android.os.Handler;
28 import android.os.Message;
29 import android.view.Menu;
30 import android.view.MenuItem;
31
32 import com.android.gallery3d.R;
33 import com.android.gallery3d.app.AbstractGalleryActivity;
34 import com.android.gallery3d.common.Utils;
35 import com.android.gallery3d.data.DataManager;
36 import com.android.gallery3d.data.MediaItem;
37 import com.android.gallery3d.data.MediaObject;
38 import com.android.gallery3d.data.Path;
39 import com.android.gallery3d.filtershow.crop.CropActivity;
40 import com.android.gallery3d.util.Future;
41 import com.android.gallery3d.util.GalleryUtils;
42 import com.android.gallery3d.util.ThreadPool.Job;
43 import com.android.gallery3d.util.ThreadPool.JobContext;
44
45 import java.util.ArrayList;
46
47 public class MenuExecutor {
48     @SuppressWarnings("unused")
49     private static final String TAG = "MenuExecutor";
50
51     private static final int MSG_TASK_COMPLETE = 1;
52     private static final int MSG_TASK_UPDATE = 2;
53     private static final int MSG_TASK_START = 3;
54     private static final int MSG_DO_SHARE = 4;
55
56     public static final int EXECUTION_RESULT_SUCCESS = 1;
57     public static final int EXECUTION_RESULT_FAIL = 2;
58     public static final int EXECUTION_RESULT_CANCEL = 3;
59
60     private ProgressDialog mDialog;
61     private Future<?> mTask;
62     // wait the operation to finish when we want to stop it.
63     private boolean mWaitOnStop;
64     private boolean mPaused;
65
66     private final AbstractGalleryActivity mActivity;
67     private final SelectionManager mSelectionManager;
68     private final Handler mHandler;
69
70     private static ProgressDialog createProgressDialog(
71             Context context, int titleId, int progressMax) {
72         ProgressDialog dialog = new ProgressDialog(context);
73         dialog.setTitle(titleId);
74         dialog.setMax(progressMax);
75         dialog.setCancelable(false);
76         dialog.setIndeterminate(false);
77         if (progressMax > 1) {
78             dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
79         }
80         return dialog;
81     }
82
83     public interface ProgressListener {
84         public void onConfirmDialogShown();
85         public void onConfirmDialogDismissed(boolean confirmed);
86         public void onProgressStart();
87         public void onProgressUpdate(int index);
88         public void onProgressComplete(int result);
89     }
90
91     public MenuExecutor(
92             AbstractGalleryActivity activity, SelectionManager selectionManager) {
93         mActivity = Utils.checkNotNull(activity);
94         mSelectionManager = Utils.checkNotNull(selectionManager);
95         mHandler = new SynchronizedHandler(mActivity.getGLRoot()) {
96             @Override
97             public void handleMessage(Message message) {
98                 switch (message.what) {
99                     case MSG_TASK_START: {
100                         if (message.obj != null) {
101                             ProgressListener listener = (ProgressListener) message.obj;
102                             listener.onProgressStart();
103                         }
104                         break;
105                     }
106                     case MSG_TASK_COMPLETE: {
107                         stopTaskAndDismissDialog();
108                         if (message.obj != null) {
109                             ProgressListener listener = (ProgressListener) message.obj;
110                             listener.onProgressComplete(message.arg1);
111                         }
112                         mSelectionManager.leaveSelectionMode();
113                         break;
114                     }
115                     case MSG_TASK_UPDATE: {
116                         if (mDialog != null && !mPaused) mDialog.setProgress(message.arg1);
117                         if (message.obj != null) {
118                             ProgressListener listener = (ProgressListener) message.obj;
119                             listener.onProgressUpdate(message.arg1);
120                         }
121                         break;
122                     }
123                     case MSG_DO_SHARE: {
124                         ((Activity) mActivity).startActivity((Intent) message.obj);
125                         break;
126                     }
127                 }
128             }
129         };
130     }
131
132     private void stopTaskAndDismissDialog() {
133         if (mTask != null) {
134             if (!mWaitOnStop) mTask.cancel();
135             if (mDialog != null && mDialog.isShowing()) mDialog.dismiss();
136             mDialog = null;
137             mTask = null;
138         }
139     }
140
141     public void resume() {
142         mPaused = false;
143         if (mDialog != null) mDialog.show();
144     }
145
146     public void pause() {
147         mPaused = true;
148         if (mDialog != null && mDialog.isShowing()) mDialog.hide();
149     }
150
151     public void destroy() {
152         stopTaskAndDismissDialog();
153     }
154
155     private void onProgressUpdate(int index, ProgressListener listener) {
156         mHandler.sendMessage(
157                 mHandler.obtainMessage(MSG_TASK_UPDATE, index, 0, listener));
158     }
159
160     private void onProgressStart(ProgressListener listener) {
161         mHandler.sendMessage(mHandler.obtainMessage(MSG_TASK_START, listener));
162     }
163
164     private void onProgressComplete(int result, ProgressListener listener) {
165         mHandler.sendMessage(mHandler.obtainMessage(MSG_TASK_COMPLETE, result, 0, listener));
166     }
167
168     public static void updateMenuOperation(Menu menu, int supported) {
169         boolean supportDelete = (supported & MediaObject.SUPPORT_DELETE) != 0;
170         boolean supportRotate = (supported & MediaObject.SUPPORT_ROTATE) != 0;
171         boolean supportCrop = (supported & MediaObject.SUPPORT_CROP) != 0;
172         boolean supportTrim = (supported & MediaObject.SUPPORT_TRIM) != 0;
173         boolean supportMute = (supported & MediaObject.SUPPORT_MUTE) != 0;
174         boolean supportShare = (supported & MediaObject.SUPPORT_SHARE) != 0;
175         boolean supportSetAs = (supported & MediaObject.SUPPORT_SETAS) != 0;
176         boolean supportShowOnMap = (supported & MediaObject.SUPPORT_SHOW_ON_MAP) != 0;
177         boolean supportCache = (supported & MediaObject.SUPPORT_CACHE) != 0;
178         boolean supportEdit = (supported & MediaObject.SUPPORT_EDIT) != 0;
179         boolean supportInfo = (supported & MediaObject.SUPPORT_INFO) != 0;
180         boolean supportPrint = (supported & MediaObject.SUPPORT_PRINT) != 0;
181
182         setMenuItemVisible(menu, R.id.action_delete, supportDelete);
183         setMenuItemVisible(menu, R.id.action_rotate_ccw, supportRotate);
184         setMenuItemVisible(menu, R.id.action_rotate_cw, supportRotate);
185         setMenuItemVisible(menu, R.id.action_crop, supportCrop);
186         setMenuItemVisible(menu, R.id.action_trim, supportTrim);
187         setMenuItemVisible(menu, R.id.action_mute, supportMute);
188         // Hide panorama until call to updateMenuForPanorama corrects it
189         setMenuItemVisible(menu, R.id.action_share_panorama, false);
190         setMenuItemVisible(menu, R.id.action_share, supportShare);
191         setMenuItemVisible(menu, R.id.action_setas, supportSetAs);
192         setMenuItemVisible(menu, R.id.action_show_on_map, supportShowOnMap);
193         setMenuItemVisible(menu, R.id.action_edit, supportEdit);
194         // setMenuItemVisible(menu, R.id.action_simple_edit, supportEdit);
195         setMenuItemVisible(menu, R.id.action_details, supportInfo);
196         setMenuItemVisible(menu, R.id.print, supportPrint);
197     }
198
199     public static void updateMenuForPanorama(Menu menu, boolean shareAsPanorama360,
200             boolean disablePanorama360Options) {
201         setMenuItemVisible(menu, R.id.action_share_panorama, shareAsPanorama360);
202         if (disablePanorama360Options) {
203             setMenuItemVisible(menu, R.id.action_rotate_ccw, false);
204             setMenuItemVisible(menu, R.id.action_rotate_cw, false);
205         }
206     }
207
208     private static void setMenuItemVisible(Menu menu, int itemId, boolean visible) {
209         MenuItem item = menu.findItem(itemId);
210         if (item != null) item.setVisible(visible);
211     }
212
213     private Path getSingleSelectedPath() {
214         ArrayList<Path> ids = mSelectionManager.getSelected(true);
215         Utils.assertTrue(ids.size() == 1);
216         return ids.get(0);
217     }
218
219     private Intent getIntentBySingleSelectedPath(String action) {
220         DataManager manager = mActivity.getDataManager();
221         Path path = getSingleSelectedPath();
222         String mimeType = getMimeType(manager.getMediaType(path));
223         return new Intent(action).setDataAndType(manager.getContentUri(path), mimeType);
224     }
225
226     private void onMenuClicked(int action, ProgressListener listener) {
227         onMenuClicked(action, listener, false, true);
228     }
229
230     public void onMenuClicked(int action, ProgressListener listener,
231             boolean waitOnStop, boolean showDialog) {
232         int title;
233         switch (action) {
234             case R.id.action_select_all:
235                 if (mSelectionManager.inSelectAllMode()) {
236                     mSelectionManager.deSelectAll();
237                 } else {
238                     mSelectionManager.selectAll();
239                 }
240                 return;
241             case R.id.action_crop: {
242                 Intent intent = getIntentBySingleSelectedPath(CropActivity.CROP_ACTION);
243                 ((Activity) mActivity).startActivity(intent);
244                 return;
245             }
246             case R.id.action_edit: {
247                 Intent intent = getIntentBySingleSelectedPath(Intent.ACTION_EDIT)
248                         .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
249                 ((Activity) mActivity).startActivity(Intent.createChooser(intent, null));
250                 return;
251             }
252             case R.id.action_setas: {
253                 Intent intent = getIntentBySingleSelectedPath(Intent.ACTION_ATTACH_DATA)
254                         .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
255                 intent.putExtra("mimeType", intent.getType());
256                 Activity activity = mActivity;
257                 activity.startActivity(Intent.createChooser(
258                         intent, activity.getString(R.string.set_as)));
259                 return;
260             }
261             case R.id.action_delete:
262                 title = R.string.delete;
263                 break;
264             case R.id.action_rotate_cw:
265                 title = R.string.rotate_right;
266                 break;
267             case R.id.action_rotate_ccw:
268                 title = R.string.rotate_left;
269                 break;
270             case R.id.action_show_on_map:
271                 title = R.string.show_on_map;
272                 break;
273             default:
274                 return;
275         }
276         startAction(action, title, listener, waitOnStop, showDialog);
277     }
278
279     private class ConfirmDialogListener implements OnClickListener, OnCancelListener {
280         private final int mActionId;
281         private final ProgressListener mListener;
282
283         public ConfirmDialogListener(int actionId, ProgressListener listener) {
284             mActionId = actionId;
285             mListener = listener;
286         }
287
288         @Override
289         public void onClick(DialogInterface dialog, int which) {
290             if (which == DialogInterface.BUTTON_POSITIVE) {
291                 if (mListener != null) {
292                     mListener.onConfirmDialogDismissed(true);
293                 }
294                 onMenuClicked(mActionId, mListener);
295             } else {
296                 if (mListener != null) {
297                     mListener.onConfirmDialogDismissed(false);
298                 }
299             }
300         }
301
302         @Override
303         public void onCancel(DialogInterface dialog) {
304             if (mListener != null) {
305                 mListener.onConfirmDialogDismissed(false);
306             }
307         }
308     }
309
310     public void onMenuClicked(MenuItem menuItem, String confirmMsg,
311             final ProgressListener listener) {
312         final int action = menuItem.getItemId();
313
314         if (confirmMsg != null) {
315             if (listener != null) listener.onConfirmDialogShown();
316             ConfirmDialogListener cdl = new ConfirmDialogListener(action, listener);
317             new AlertDialog.Builder(mActivity.getAndroidContext())
318                     .setMessage(confirmMsg)
319                     .setOnCancelListener(cdl)
320                     .setPositiveButton(R.string.ok, cdl)
321                     .setNegativeButton(R.string.cancel, cdl)
322                     .create().show();
323         } else {
324             onMenuClicked(action, listener);
325         }
326     }
327
328     public void startAction(int action, int title, ProgressListener listener) {
329         startAction(action, title, listener, false, true);
330     }
331
332     public void startAction(int action, int title, ProgressListener listener,
333             boolean waitOnStop, boolean showDialog) {
334         ArrayList<Path> ids = mSelectionManager.getSelected(false);
335         stopTaskAndDismissDialog();
336
337         Activity activity = mActivity;
338         if (showDialog) {
339             mDialog = createProgressDialog(activity, title, ids.size());
340             mDialog.show();
341         } else {
342             mDialog = null;
343         }
344         MediaOperation operation = new MediaOperation(action, ids, listener);
345         mTask = mActivity.getBatchServiceThreadPoolIfAvailable().submit(operation, null);
346         mWaitOnStop = waitOnStop;
347     }
348
349     public void startSingleItemAction(int action, Path targetPath) {
350         ArrayList<Path> ids = new ArrayList<Path>(1);
351         ids.add(targetPath);
352         mDialog = null;
353         MediaOperation operation = new MediaOperation(action, ids, null);
354         mTask = mActivity.getBatchServiceThreadPoolIfAvailable().submit(operation, null);
355         mWaitOnStop = false;
356     }
357
358     public static String getMimeType(int type) {
359         switch (type) {
360             case MediaObject.MEDIA_TYPE_IMAGE :
361                 return GalleryUtils.MIME_TYPE_IMAGE;
362             case MediaObject.MEDIA_TYPE_VIDEO :
363                 return GalleryUtils.MIME_TYPE_VIDEO;
364             default: return GalleryUtils.MIME_TYPE_ALL;
365         }
366     }
367
368     private boolean execute(
369             DataManager manager, JobContext jc, int cmd, Path path) {
370         boolean result = true;
371         Log.v(TAG, "Execute cmd: " + cmd + " for " + path);
372         long startTime = System.currentTimeMillis();
373
374         switch (cmd) {
375             case R.id.action_delete:
376                 manager.delete(path);
377                 break;
378             case R.id.action_rotate_cw:
379                 manager.rotate(path, 90);
380                 break;
381             case R.id.action_rotate_ccw:
382                 manager.rotate(path, -90);
383                 break;
384             case R.id.action_toggle_full_caching: {
385                 MediaObject obj = manager.getMediaObject(path);
386                 int cacheFlag = obj.getCacheFlag();
387                 if (cacheFlag == MediaObject.CACHE_FLAG_FULL) {
388                     cacheFlag = MediaObject.CACHE_FLAG_SCREENNAIL;
389                 } else {
390                     cacheFlag = MediaObject.CACHE_FLAG_FULL;
391                 }
392                 obj.cache(cacheFlag);
393                 break;
394             }
395             case R.id.action_show_on_map: {
396                 MediaItem item = (MediaItem) manager.getMediaObject(path);
397                 double latlng[] = new double[2];
398                 item.getLatLong(latlng);
399                 if (GalleryUtils.isValidLocation(latlng[0], latlng[1])) {
400                     GalleryUtils.showOnMap(mActivity, latlng[0], latlng[1]);
401                 }
402                 break;
403             }
404             default:
405                 throw new AssertionError();
406         }
407         Log.v(TAG, "It takes " + (System.currentTimeMillis() - startTime) +
408                 " ms to execute cmd for " + path);
409         return result;
410     }
411
412     private class MediaOperation implements Job<Void> {
413         private final ArrayList<Path> mItems;
414         private final int mOperation;
415         private final ProgressListener mListener;
416
417         public MediaOperation(int operation, ArrayList<Path> items,
418                 ProgressListener listener) {
419             mOperation = operation;
420             mItems = items;
421             mListener = listener;
422         }
423
424         @Override
425         public Void run(JobContext jc) {
426             int index = 0;
427             DataManager manager = mActivity.getDataManager();
428             int result = EXECUTION_RESULT_SUCCESS;
429             try {
430                 onProgressStart(mListener);
431                 for (Path id : mItems) {
432                     if (jc.isCancelled()) {
433                         result = EXECUTION_RESULT_CANCEL;
434                         break;
435                     }
436                     if (!execute(manager, jc, mOperation, id)) {
437                         result = EXECUTION_RESULT_FAIL;
438                     }
439                     onProgressUpdate(index++, mListener);
440                 }
441             } catch (Throwable th) {
442                 Log.e(TAG, "failed to execute operation " + mOperation
443                         + " : " + th);
444             } finally {
445                onProgressComplete(result, mListener);
446             }
447             return null;
448         }
449     }
450 }